Dependency Injection – How to Use DI and DI Containers

dependency-injectiondesigndesign-patternsPHP

I am building a small PHP mvc framework (yes, yet another one), mostly for learning purposes, and I am trying to do it the right way, so I'd like to use a DI container, but I am not asking which one to use but rather how to use one.

Without going into too much detail, the mvc is divided into modules which have controllers which render views for actions. This is how a request is processed:

  • a Main object instantiates a Request object, and a Router, and injects the Request into the Router to figure out which module was called.
  • then it instantiates the Module object and sends the Request to that
  • the Module creates a ModuleRouter and sends the Request to figure out the controller and action
  • it then creates the Controller and the ViewRenderer, and injects the ViewRenderer into the Controller (so that the controller can send data to the view)
  • the ViewRenderer needs to know which module, controller and action were called to figure out the path to the view scripts, so the Module has to figure out this and inject it to the ViewRenderer
  • the Module then calls the action method on the controller and calls the render method on the ViewRenderer

For now, I do not have any DI container set up, but what I do have are a bunch of initX() methods that create the required component if it is not already there.
For instance, the Module has the initViewRenderer() method.
These init methods get called right before that component is needed, not before, and if the component was already set it will not initialize it. This allows for the components to be switched, but it does not require manually setting them if they are not there.

Now, I'd like to do this by implementing a DI container, but still keep the manual configuration to a bare minimum, so if the directory structure and naming convention is followed, everything should work, without even touching the config.

If I use the DI container, do I then inject it into everything (the container would inject itself when creating a component), so that other components can use it?
When do I register components with the DI?
Can a component register other components with the DI during run-time?
Do I create a 'common' config and use that?
How do I then figure out on the fly which components I need and how they need to be set up?

If Main uses Router which uses Request,
Main then needs to use the container to get Module (or does the module need to be found and set beforehand? How?)
Module uses Router but needs to figure out the settings for the ViewRenderer and the Controller on the fly, not in advance, so my DI container can't be setting those on the Module before the module figures out the controller and action…

What if the controller needs some other service? Do I inject the container into every controller? If I start doing that, I might just inject it into everything…

Basically I am looking for the best practices when dealing with stuff like this. I know what DI is and what DI containers do, but I am looking for guidance to using them in real life, and not some isolated examples on the net.

Sorry for the lengthy post and many thanks in advance.

EDIT: after reading a bit more, it seems that injection the container itself into objects and making them use the container to find stuff is actually service location, not dependency injection. So my latest idea is to use factories for the stuff that should be dynamically acquired based on something (like getting controllers based on what the router says), and the container would be injected into the factories where it would be used more like a service locator. The non dynamic components would be registered beforehand, and those components would be built by the container and returned fully operational, with all their dependencies filled.

So the flow would look like this:

  • get Main from the container, Main is injected with Request, Router and ModuleFactory which uses the container to find modules. This is all pre-configured
  • Main uses ModuleFactory to create the Module, injected with ModuleRouter, Request, ControllerFactory and ViewRenderer.
  • Module uses ControllerFactory to create a Controller, injected with any service that it depends on, and then the Module calls the action on the controller, and sends the result to the ViewRenderer to render the view.

Am I getting anywhere with this?

Best Answer

As there is no right or wrong in this question, I could give an example about how I like to use Dependency Injection in PHP.

I'm using the Dependency Injection Component from Symfony with the LosoDiAnnotationsBundle and extracted everything from the Bundle to use it as standalone as the Dependency Injection Component. I'm not using the rest of the Symfony Framework.

There are two functions in my system which use the Dependency Injection Container. The main function and the dispatcher. The main function (application entry point) retrieves the configured Dispatcher like this:

$dispatcher = $service_container->get('Dispatcher');
$response = $dispatcher->route( $request );

The service called "Dispatcher" is either defined in the global dependency config or annotated in the class itself like this:

 /*
 * @Service
 */
 class Dispatcher {
    /**
     * @Inject({"@service_container"})
     */
    public function __construct($serviceContainer) {
        $this->serviceContainer  = $serviceContainer;
    }
 }

The Dispatcher needs this service locator because thats how my routing works. If you use some extra mapping between routes and called methods, you could avoid this.

To inject something into other services I use the @inject annotation:

/** @Inject({"@SomeLogic", "@SomeGateway"}) */
public function setDependencies(SomeLogic $someLogic, SomeGateway $someGateway) {
    $this->someLogic = $someLogic;
    $this->someGateway = $someGateway;
}

I like this approach because the configuration of a Service Class is done in the class itself and not in a separate file. Refactoring doesn't involve messing around with lengthy XML or YAML files.

To not harm the performance I run a script everytime I change some annotations and at build time (or in general on every vagrant up). It uses Symfony's ContainerBuilder and PHP Dumper to generate a PHP Lookup file which extends the Base ServiceContainer Class.

The lookup for the example dispatcher would look like this:

protected function getDispatcherService()
{
    return $this->services['dispatcher'] = new \Some\Dispatcher($this);
}

This looks like a lot of work upfront, but it clearly separates concerns later on, especially in bigger projects. Classes do what they are supposed to do and need little to no non-domain-logic code at all.

And I try to keep factories to an absolutely minimum. The DI Container itself is one big factory and repository but it is not manually maintained.

EDIT:

My Routing Function looks like this, request_uri is something like Controller/action/...

    $path = explode( self::ACTION_SEPARATOR, $request_uri );

    if( empty( $path[1] ))
        throw new RoutingException( 'Invalid Action' );

    $method = ucfirst( $path[1] );
    $className = $path[0].'Controller';
    $qualifiedClassName = 'Some\\Namespace\\'.$className;

    if( !class_exists( $qualifiedClassName ))
        throw new RoutingException(sprintf('Invalid controller "%s" for route "%s"', $qualifiedClassName, $route));
    if( !is_callable( array( $qualifiedClassName, $method ) ))
        throw new RoutingException(sprintf('Invalid Action "%s"', $method));


    $controller = $this->serviceContainer->get( $className );
    call_user_func( array( $controller, $method ), $message );
Related Topic