6

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?

6
  • even if you don't want to have a discussion about which framework to use, you should look into different implementations and learn how they utilize the DI. i like the DI stuff from symfony extended by some custom code to use annotations on service classes. Sep 3, 2012 at 15:04
  • what I am trying to avoid is getting a DI framework and then (ab)using it in a completely wrong way. I'd like to know what I am doing before I start wiring stuff up around a framework or DI container. Having said that, I will take your advice and take a look at Symfony's DI to see if I can get something from there. Sep 3, 2012 at 15:12
  • i understand you concerns and appreciate your approach. i just wanted to say to take a look how others do it in order to adept it to your own problem domain. Sep 3, 2012 at 15:31
  • This will be a controversial comment, but: Don't try too hard to follow "good practices". The fact is, there is no right answer, because there is no wrong answer. Some people will tell you to do a, others will tell you b, and eventually you end up in code that is more complicated than it should because you are trying to honor the opinion of everyone on how something should be done. I personally think DI injection is not a bad idea if you want your code to be testable, but building several extra factories just because someone doesn't like DI containers, I'd start questioning if it's worth it.
    – Mahn
    Sep 3, 2012 at 15:48
  • @Mahn, the thing is, I feel like I do not have enough experience to make an informed decision when to use and when not to use "best practices". Because I've caught myself overcomplicating things early, and then simplifying them, just to figure out that the first overcomplication was actually necessary later on. So I am trying to at least grasp the theory of the thing as best I can. Sep 4, 2012 at 12:19

2 Answers 2

2

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 );
5
  • I get the part where you wire up the container up front and all that. But what if you have to figure out which object to instantiate on the fly? For instance, my Module class could be extended by the user, and the program has to figure out that on the fly, by checking if such a file and class exists (there's a convention to follow). If it exists, it should use that, if not, use the base Module class. Isn't that a job for some sort of Factory or whatnot? Sep 3, 2012 at 21:24
  • does my EDIT clarifies this? you could also check the existance of some service in there with $serviceContainer->has("serviceName") for your fallback modules. Sep 4, 2012 at 12:10
  • Oh I get it, so where I'd use a factory, you just use the container itself. So basically the objects that need to find other objects on the fly, they are injected with the container, not factories? I gave you a +1 for the answer, and will accept it after you confirm this last concern I have. Sep 4, 2012 at 12:17
  • you're right. basically every module class would be defined as a service in the container, even the base module. the container itself is a big factory ;) Sep 4, 2012 at 14:11
  • 1
    ok, this clears things up quite a bit, so here are your due points. Sep 4, 2012 at 14:15
1

I know its kind of a counter argument but I think it would be beneficial for you to look beyond DI.

Think about the properties of DI and what you are trying to do with applying it.

Here is a video, different aspects of programming styles are discussed(arround 25 min the case for DI is made) http://www.infoq.com/presentations/Value-Values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.