PHP MVC: Too many dependencies in controller?

2019-02-20 17:24发布

问题:

I'm working on a personal HMVC project:

  • No service locators, no global state (like static or global), no singletons.
  • The model handling is encapsulated in services (service = domain objects + repositories + data mappers).
  • All controllers extend an abstract controller.
  • All project dependencies are injected through Auryn dependency injection container.

All needed dependencies are injected in the constructor of the abstract controller. If I want to override this constructor, then I have to pass all these dependencies in the child controller's constructor too.

class UsersController extends AbstractController {

    private $authentication;

    public function __construct(
        Config $config
        , Request $request
        , Session $session
        , View $view
        , Response $response
        , Logger $logger
        , Authentication $authentication // Domain model service
    ) {
        parent::__construct(/* All dependencies except authentication service */);
        $this->authentication = $authentication;
    }

    // Id passed by routing.
    public function authenticateUser($id) {
        // Use the authentication service...
    }

}

The dependencies list would further grow. This needs to change. So I was thinking about:

  • Totally separate controllers from views.
    They would then share the service layer. The views wouldn't belong to controllers anymore and the Response would be a dependency of the views.
  • Use setter injection in controllers
    Like for Request, Session, Logger, etc;
  • Inject dependencies in the controller actions
    Only when needed.
    Like for Request, Session, Logger, etc;
  • Use decorator pattern.
    Like for logging after an action call.
  • Implement some factories.
  • To constructor inject only the needed dependencies only on child controllers.
    So not in AbstractController anymore.

I'm trying to find an elegant way to deal with this task and I'll appreciate any suggestions. Thank you.

回答1:

I'll answer to my own question. When I wrote it I already had a good overview of what many experienced developers recommend regarding dependency injection in MVC and MVC structure.

  • The constructor injection is the proper option. But it seemed to me that, following this line, I'll end up with too many dependencies/arguments in constructors. Therefore giving controllers too many responsibilities (reading the requested values, changing the state of the domain objects, logging operations, requesting the view to load the templates and to render the data, etc).
  • Setter injection was also a solution to take in consideration. But, in the course of the developing time on my project, I realised that this solution really didn't fit (at least) into the picture of my controller-view relationships.
  • The injection of the dependencies directly into the controller actions caused me hard-time (but great time) too, having in mind that I already had the url values injected as action arguments and that I didn't used any routing dispatchers.
  • Implementing factories was also a great idea, in order to be able to have objects at my disposal within each controller action. Factories are a great tool to use, but only going from the premise of needed run-time objects, not of just reducing the number of dependencies in constructors.
  • Decorator pattern is also a good alternative. But if, for example, you want to log something within a controller action, then this is not a solution: you still have to pass a logger as dependency (in constructor, setter or action).
  • I had a thought about injecting the needed dependencies only on child controllers. But then the problem of multiple responsibilities of the corresponding controllers remains the same.

So, none of this solutions seemed to entirely fit into the structure of my HMVC project, whatever I did. So, i dug further, until I realised what the missing link was. For this I give my whole appreciation to Tom Butler, the creator of the following great articles:

  • Model-View-Confusion part 1: The View gets its own data from the Model
  • Model-View-Confusion part 2: MVC models are not domain models


His works are based on an in-depth, well argumented analyse of the MVC concepts. They are not only very easy to follow, but also sustained by self-explanatory examples. In a word: a wonderful contribution to the MVC and developer community.

What I'll write further is meant to be just a presentation of his principles with my own words, having in mind to somehow complete them, to provide a compacter perspective of them and to show the steps followed by me when I implemented them in my project. All credit on the subject, ideas and principles and workflows depicted here goes to Tom Butler.

So, what was the missing link in my HMVC project? It's named SEPARATION OF CONCERNS.

For simplicity I'll try to explain this by referring myself to only one controller, one controller action, one view, one model (domain object) and one template (file), introducing them into a User context.

The MVC concept most described on web - and also implemented by some popular frameworks that I studied - is centered around the principle of giving the controller the control over the view and the model. In order to display something on screen you'll have to tell that to the controller - he further notifies the view to load and render the template. If this display process implies the use of some model data too, then the controller manipulates the model too.

In a classical way, the controller creation and action calling process involve two steps:

  • Create the controller - passing it all dependencies, view inclusive;
  • Call the controller action.

The code:

$controller = new UserController(/* Controller dependencies */);

$controller->{action}(/* Action dependencies */);

This implies, that the controller is responsible for, well, everything. So, no wonder why a controller must be injected with so many dependencies.

But should the controller be involved in, or responsible for effectively displaying any kind of information on the screen? No. This should be the responsibility of the view. In order to achieve this let's begin separating the view from the controller - going from the premise of not needing any model yet. The involved steps would be:

  • Define an output method for displaying information on screen in the view.
  • Create the controller - passing it all dependencies, excepting the view and its related dependencies (response, template object, etc).
  • Create the view - passing it the corresponding dependencies (response, template object, etc).
  • Call the controller action.
  • Call the output method of the view:

And the code:

class UserView {
    //....
    // Display information on screen.
    public function output () {
        return $this
                    ->load('<template-name>')
                    ->render(array(<data-to-display>))
        ;
    }
    //....
}

$controller = new UserController(/* (less) controller dependencies */);
$view = new UserView(/* View dependencies */);

$controller->{action}(/* Action dependencies */);
echo $view->output();

By accomplishing the five upper steps we managed to completely decouple the controller from the view.

But, there is an aspect, that we hypothesised earlier: we did not made use of any model. So what's the role of the controller in this constellation then? The answer is: none. The controller should exist only as a middlemann between some storage place (database, file system, etc) and the view. Otherwise, e.g. only to output some information in a certain format on screen, is the output method of the view fully sufficient.

Things change if a model is beeing brought on the scene. But where should it be injected? In the controller or in the view? In both. They share the same model instance. In this moment the controller gains the role of the middleman - between storage and view - in his own right. A theoretical form would be:

$model = new UserModel;
$controller = new UserController($model, /* Other controller dependencies */);
$view = new UserView($model, /* Other view dependencies */);

$controller->{action}(/* Action dependencies */);
echo $view->output();

Doing so, the controller can change the state of the model and ensure that it's saved in the storage system. The same model instance, respective its state, is read by the view and displayed. The controller passes display logic informations to the view through the model. The problem is, that these informations don't belong to the business logic, which a model is supposed to exclusively have. They are only display logic participants.

In order to avoid giving display logic responsibilities to the model, we have to introduce a new component in the picture: the view-model. Instead of sharing a model object, the controller and the view will share a view-model instance. Only this one will receive the model as dependency. An implementation:

$model = new UserModel;
$viewModel = new UserViewModel($model, /* Other view-model dependencies */);
$controller = new UserController($viewModel /* Other controller dependencies */);
$view = new UserView($viewModel, /* Other view dependencies */);

$controller->{action}(/* Action dependencies */);
echo $view->output();

And the workflow can be described like this:

  • The request values are sent by the browser ("the user") to the controller.
  • The controller stores them in the view-model instance as properties (data members), therefore changing the display logic state of the view-model.
  • Within its output method, the view reads the values from the view-model and requests the model to query the storage on their basis.
  • The model runs the corresponding query and passes the results back to the view.
  • The view reads and passes them to the corresponding template.
  • After template rendering, the results are displayed on the screen.

The view-model does not belong to the domain model, where all domain objects reside and the real business logic takes place. It does also not belong to the service layer, which manipulates the domain objects, repositories and data mappers. It belongs to the application model, e.g to the place where the application logic takes place. The view-model obtains the sole responsibility of gaining display logic state from the controller and conducting it to the controller.

As can be seen, only the view-model "touches" the model. Both, the controller and the view were not only completely decoupled from each other, but also from the model. The most important aspect of this approach is, that each of all the components involved gains only the responsibilities, that it is supposed to gain.

By making use of this kind of component separation and of a dependency injection container, the problem of too many dependencies in controllers vanishes. And one can apply a combination of all options presented in my question in a really flexible manner. Without having in mind that one of the components (model, view or controller) gains too many responsibilities.