concept controller in category design

appears as: controller, controllers, controller, The controller, A controller
Object Design Style Guide

This is an excerpt from Manning's book Object Design Style Guide.

Once the application framework calls your controller (be it a web controller or a controller for a command-line application), you can consider every dependency to be known. For instance, the web controller needs a repository to fetch some objects from, it needs the templating engine to render a template, it needs a response factory to create a response object, etc. All these dependencies have their own dependencies, which, when carefully listed as constructor arguments, can be created at once, resulting in an often pretty large graph of objects.

If the framework decides to call a different controller, it will use a different graph of dependent objects to perform its task. The controller itself is also a service with dependencies, so you can consider controllers to be the entry points of the application’s object graph, as shown in figure 2.4.

we should conclude that the service container only needs to provide public methods for retrieving controllers. The other services defined in the container can and should remain private, because they will only be needed as injected dependencies for controllers.

Translated to code, this means we could use a service container as a service locator to retrieve a controller from. All the other service instantiation logic that’s needed to produce the controller objects can stay behind the scenes, in private methods.

Listing 2.39. Public methods for entry points, private ones for dependencies
final class ServiceContainer
{
    public function homepageController(): HomepageController
    {
        return new HomepageController(
            this.userRepository(),
            this.responseFactory(),
            this.templateRenderer()
        );
    }

    private function userRepository(): UserRepository
    {
        // ...
    }

    private function responseFactory(): ResponseFactory
    {
        // ...
    }

    private function templateRenderer(): TemplateRenderer
    {
        // ...
    }

    // ...
}

if (uri == '/') {                                        #1
    controller = serviceContainer.homepageController();
    response = controller.execute(request);
    // ...
} elseif (/* ... */) {
    // ...                                               #2
}

A service container allows for reuse of services, which is why, starting with the controller as an entry point, not every branch of the object graph will be completely standalone. For example, another controller may use the same TemplateRenderer instance as HomepageController (see figure 2.5). This is why it’s important to make services behave as predictably as possible. If you apply all the previously discussed rules, you will end up with an object graph that can be instantiated once, and then reused many times.