Function reuse when using Class:method for routing

Hello @eddieaich

Be careful, that you don’t mix the MVC layers together. The controller layer should be very thin, and the model layer can be “fat”. This means, put all all the “businsess logic” (calculation) into the “domain service layer” and all the database queries into the “data access layer” Example. The controller just calls the service and the services fetches or updates data in the database (via the Repository). Then, within the controller, use the return value of the service to generate the json response. Then you can reuse all the Repository methods like you want.

Data flow: Client request > Router > Controller Action > Service class > Repository > and back

In your case I would create a Repository class e.g. TicketRepository.php with a public method like getTicketStatuses().

Example:

namespace App\Domain\Ticket;

class TicketRepository
{
    // e.g. PDO
    protected $connection;

    public function __construct(Connection $connection)
    {
        $this->connection= $connection;
    }
 
    public function getTicketStatuses(): array
    {
        // fetch data here 
        // $this->connection->...
        return [];
    }

    public function getTicketTypes(): array
    {
        // fetch data here 
        // $this->connection->...
        return [];
    }
}

If you have more logic (calculation, validation, logging) then create a service class and call it from the controller.

namespace App\Domain\Ticket;

class TicketService
{
    protected $repository;

    public function __construct(TicketRepository $repository)
    {
        $this->repository = $repository;
    }
 
    public function getCommonData(): array
    {
        // do something more complex here, like validation etc.
        return [
            'statuses' => $this->repository->getTicketStatuses(),
            'types' => $this->repository->getTicketTypes(),
       ];
    }
}
1 Like