Skip to content
Advertisement

Should Controller Layer cannot use Repository Layer?

I’m confused about Controller use Repository directly.

Is it Repository layer must encapsulated by Service layer?

I’m using like this now in Laravel:

class SomeController
{
    private SomeRepository $someRepository;

    public __construct(SomeRepository $someRepository)
    {
        $this->someRepository = $someRepository;
    }
}

Is is Bad to use Repository Layer directly from Controller Layer?

Advertisement

Answer

Note: In regard of MVC-based applications, this answer is a general one. It does not refer to Laravel, in particular.

The controller:

In a proper MVC implementation, a controller should have one responsibility: to take the user input and to update the domain model with it. So, a controller method should contain just a few lines of code (2-3). The whole steps involved in updating the model, e.g. the corresponding application logic, should therefore be delegated to other components: the services of the service layer.

Having the above in mind, it is not good to directly inject data mappers or repositories – as an additional layer to the data mappers layer – into controllers, instead of services, because the whole application logic of updating the model layer would then reside in the controller methods.

The view:

The view component (the “V” in “MVC”, composed of various classes, not only of template files like “users_list.html.twig”) should only be responsible with reading proper data from the domain model (e.g. the one updated by the controller, at least) and presenting it to the user (by loading and rendering corresponding template files). The view should therefore receive services as dependencies too; even the ones received by the controller.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement