6.0.0-git
2024-10-06
Last Modified 2010-01-15 by Chuck Hagenbuch

Introduction

The dependency injection pattern (http://en.wikipedia.org/wiki/Dependency_injection) is a useful approach that can help to avoid using global variables or state. If a class depends on a connection to a database then this connection is often pulled into the class using a singleton pattern or by using a global variable.

Instead of providing the class with knowledge about the global state it is often preferable to "inject" the dependency into the class from the outside. This usually happens within the class constructor. To get hold of a database connection a class constructor could for example require an object that implements a database interface instead of using a singleton pattern.

This way the dependencies of a class are immediately visible in the constructor. It is not necessary to search the code of the class for references to the global scope. This usually also helps to decouple
dependencies between different code modules. Another major benefit of dependency injection is the fact that it facilitates unit testing of complex systems.

Horde_Injector

Horde_Injector provides a "Dependency Injection" framework. For PHP there exist several dependency injection frameworks (e.g. http://stubbles.net, http://components.symfony-project.org/dependency-injection) with extensive feature lists. So there is hardly any need for another framework with similar capabilities.

The essential part of dependency injection is the structure of classes with dependencies. They need to be amenable for an external management of their dependencies. If that is the case for a given class then most dependency injection frameworks should have no problem handling this class within the framework. The choice of the actual framework should not matter anymore.

Horde_Injector provides only a minimal version of dependency injection. It is somewhere in between the frameworks mentioned above and Twittee (http://twittee.org/). The primary goal is to drive refactoring of classes with complex dependencies so that their dependencies can be uncoupled and they can be used with a dependency injection framework.

Making classes amenable to dependency injection

As trivial as it may sound: a class can be managed by a dependency injection framework if the class allows the framework to inject its dependencies from the outside. That means that the class may not

  • pull in a dependency using global state via the singleton pattern:

External_Class::singleton();

  • create new objects with dependencies:

$db = new DB();
$b = new User($db);

  • use global variables:

global $conf;
$db = new DB($conf['sql');

In most cases the class should receive dependencies and required parameters within the constructor.

Using Horde_Injector

The Horde_Injector class is a simple container that allows you to fill it with a number of elements that can be retrieved later:

$a = new Horde_Injector(new Horde_Injector_TopLevel());
$a->setInstance('a', 'a');
echo $a->getInstance('a');

string(1) "a"

Here we assigned a concrete instance to the injector. In fact not even an instance but a simple type: a string. Usually you would register an object.

But there might be situations - and in fact these are what dependency injection is about - where you do not want to register a concrete instance. You might not already have all the dependencies for creating an instance in place. So all you want to do is to register the required build instruction for generating an instance.

This is something that you can do by registering a wrapper object that implements the Horde_Injector_Binder interface. This wrapper object needs to be capable of creating the concrete instance:

class Binder implements Horde_Injector_Binder
{
    public function create(Horde_Injector $injector)
    {
        return 'constructed';
    }
    public function equals(Horde_Injector_Binder $binder)
    {
        return false;
    }
}

$a = new Horde_Injector(new Horde_Injector_TopLevel());
$a->addBinder('constructed', new Binder());
var_dump($a->getInstance('constructed'));

string(11) "constructed"

The example above demonstrates this approach by using the dummy Binder class which implements Horde_Injector_Binder. Once getInstance('constructed') is called on the injector object it will
determine that there is no concrete instance for 'constructed' yet. It then looks for any binders that might be capable of creating 'constructed' and calls the create() function of such a binder.

Here the binder is simple again and does not even return an object but a simple string. It also makes no use of the Horde_Injector instance delivered as argument to the create() function. Usually the provided injector will be used to retrieve any missing dependencies for the instance to be created.

Default Binders

Horde_Injector comes with two default Binder implementations so that you don't have to define your own binders.

Lets look at the factory binder first:

class Greet
{
    public function __construct($somebody)
    {
        $this->somebody = $somebody;
    }

    public function greet()
    {
        print 'Hello ' . $this->somebody;
    }
}

class Factory
{
    static public function getGreeter(Horde_Injector $injector)
    {
        return new Greet($injector->getInstance('Person'));
    }
}
 
$a = new Horde_Injector(new Horde_Injector_TopLevel());
$a->setInstance('Person', 'Bob');
$a->bindFactory('Greet', 'Factory', 'getGreeter');
$a->getInstance('Greet')->greet();

Hello Bob

This time the Factory in the example above really pulls a dependency: a person. We explicitly registered the string "Bob" with the injector and associated it with the interface name "Person".

The Horde_Injector_Binder_Factory binder can be registered with the injector using the "bindFactory()" shortcut. It takes the interface name (here it is "Greet") and requires a class and a method name. This is assumed to be the factory creating the concrete instance.

Once getInstance('Greet') is called the injector refers to the binder (as no concrete instance has been created yet). The binder delegates to the factory to actually create the object.

The whole thing is also possible with a little bit more magic. The second approach implemented by Horde_Injector_Binder_Implementation requires type hinting to work:

interface Person
{
    public function __toString();
}

class World implements Person
{
    public function __toString()
    {
        return 'World';
    }
}

interface Greeter
{
    public function greet();
}

class Hello implements Greeter
{
    public function __construct(Person $somebody)
    {
        $this->somebody = $somebody;
    }

    public function greet()
    {
        print 'Hello ' . $this->somebody;
    }
}

$a = new Horde_Injector(new Horde_Injector_TopLevel());
$a->bindImplementation('Person', 'World');
$a->bindImplementation('Greeter', 'Hello');
$a->getInstance('Greeter')->greet();

Hello World

The crucial part here is that the "Hello" class indicates in its constructor that it requires an object implementing the interface "Person". Horde_Injector is capable of detecting this via reflection. It will automatically search for the dependency and try to create an instance implementing this interface.

In order for this to work we bind two classes to two interfaces: "World" to "Person" and "Hello" to "Greeter". Once the injector tries to create the "Greeter"-instance it will be able to fetch the required "Person" dependency by creating a "World" object.

In case you remember that printing the little resulting string can be slightly easier while even using far less code: Dependency injection is meant for complex situations.

Nevertheless the example hopefully demonstrates how to handle different implementation options using dependency injection: You may have different drivers that all fulfill a given interface. The Horde_Injector gives you an easy method to define which drivers you actually want to use without actually instantiating them. The concrete setup will only be build once you really need a concrete instance.

Preparing a class for Horde_Injector

Assume you have the following simple class that represents a common structure found in many of the Horde packages:

class Horde_X
{
    /**
     * Instance object.
     *
     * @var Horde_X
     */
    static protected $_instance;

    /**
     * Pointer to a DB instance.
     *
     * @var DB
     */
    protected $_db;

    /**
     * Attempts to return a reference to a concrete Horde_X instance.
     *
     * @return Horde_X  The concrete Horde_X reference.
     * @throws Horde_Exception
     */
    static public function singleton()
    {
        if (!isset(self::$_instance)) {
            self::$_instance = new Horde_X();
        }

        return self::$_instance;
    }

    /**
     * Constructor.
     */
    public function __construct()
    {
        global $conf;

        $this->_db = DB::connect($conf['sql']);
    }
}

The class obviously depends on a database connection. The constructor above does not allow for dependency injection as it constructs the database connection itself. It uses the global variable $conf in order to get the settings for this connection. A constructor allowing dependency injection would look like this:

    /**
     * Constructor.
     *
     * @param DB $db A database connection.
     */
    public function __construct(DB $db)
    {
        $this->_db = $db;
    }

Of course this connection must be provided from somewhere. The application using Horde_X might simply provide it when creating the Horde_X instance. If the application is however using a dependency injection framework then this framework would be required to provide the required database connection.

Getting rid of singletons?

From the viewpoint of dependency injection Horde_X can be used now as it allows external injection of its dependencies. We could throw away the singleton now. However there might be some reasons why we would like to keep the singleton() method. One of the reasons might be backward compatibility as some other classes or applications are bound to use the method. Another reason might be that we want to clarify how to get a functional instance of the class to somebody just looking at the Horde_X class.

We could keep the following singleton method:

    static public function singleton()
    {
        if (!isset(self::$_instance)) {
            global $conf;

            $db = DB::connect($conf['sql']);
            self::$_instance = Horde_X($db);
        }

        return self::$_instance;
    }

The final result that can be used with a dependency injection framework and still provides a backward compatible singleton method:

class Horde_X
{
    /**
     * Instance object.
     *
     * @var Horde_X
     */
    static protected $_instance;

    /**
     * Pointer to a DB instance.
     *
     * @var DB
     */
    protected $_db;

    /**
     * Attempts to return a reference to a concrete Horde_X instance.
     *
     * @return Horde_X  The concrete Horde_X reference.
     */
    static public function singleton()
    {
        if (!isset(self::$_instance)) {
            global $conf;

            $db = DB::connect($conf['sql']);
            self::$_instance = Horde_X($db);
        }

        return self::$_instance;
    }

    /**
     * Constructor.
     *
     * @param DB $db A database connection.
     */
    public function __construct(DB $db)
    {
        $this->_db = $db;
    }
}

Dependency Injection Container FAQ

Where can Horde_Injector be used?

In the application layer only. If you use this in your business models I will find you and beat you to death with a shoe.

How do I provide Horde_Config values to my business models?

Factories.

$injector->bindFactory('InterfaceX', 'FactoryX', 'create');

class FactoryX {
    public function create(Horde_Injector $injector) {
        $setting = $injector->getInstance('Horde_Config')->get('main', 'setting');
        return new X($setting);
    }
}

I have an array-typed parameter in my constructor, do I have to use a factory to provide the array of values?

Maybe. It depends on which you believe is easier. Consider this example where a more specific ArrayObject is used. Does this array get reused? If so it may be worth creating a special extension of ArrayObject.

$injector->bindFactory('Dictionary_Sources', 'Dictionary_Sources_Factory');
$dictionary = $injector->createInstance('Dictionary');

class Dictionary {
    public function __construct(Dictionary_Sources $sources) {
        ...
    }
}

class Dictionary_Sources extends ArrayObject{}

class Dictionary_Sources_Factory {
    public function create(Horde_Injector $injector) {
        return new Dictionary_Sources(array(
            $injector->getInstance('Dictionary_Source_Cache'),
            $injector->getInstance('Dictionary_Source_Db'),
            $injector->getInstance('Dictionary_Source_Json')
        ));
    }
}

You're probably thinking that you could just create a factory to build your Dictionary object since you need to write a factory anyways. The real benefit is when you decide that Dictionary needs a new collaborator, say a Logger. If you have defined a factory for your Dictionary object, then you must edit that factory and create a Logger and pass it to your Dictionary. With the method above, you would simply need to edit your constructor, and the Logger will be provided for you. This gives you much greater flexibility, especially if you have objects that can operate on the same array of objects, but need slightly different configuration.

Dependency Injection Container Spec


Terms

  • Dependency Injection - DI
  • Dependency Injection Container - DIC

Requirements

Switching business layer implementations across an application is expensive.

DI decouples our business layer classes from other business layer classes but doesn't solve the problem of decoupling our application layer classes from our business layer classes. Without functionality to tackle this issue, business layer class configuration is duplicated throughout the application.

As expense is the primary concern, any solution to the problem must not simply move the expense to initial application layer implementation.


Functional Spec

Goals

  • Decouple application layer (controller) from business layer (model)
  • Allow easy use of models which are decoupled from their dependencies using DI
  • Favor code over configuration
  • Simple, testable design

Features

A DIC allows you to make typically difficult configuration changes, like changing an entire application from using one service implementation to another, with simple modifications in one localized place.

A DIC manages the way your objects are wired together. It makes the wiring entirely configurable per-application, per-module, and all the way down to per single object instantiation. Needing configuration to make lots of individual objects is inefficient and hard to maintain which is why its reserved for only special cases. In reality most classes rely on only a few service objects (configuration, database connection, cache, etc.) and these object most often will have identical configurations in the entire application with a few per-module exceptions.

DICs don't require configuration for every object you want them to create. In most cases class dependencies will be detectable and the DIC will be able to provide those dependencies automatically.

Using a DIC for all application-level object creation makes your application unit-testable. Dependencies can easily be swapped out with mock objects because all dependencies are provided to the application using a DIC.


Technical Spec

The name of our DIC implementation is Horde_Injector. Horde_Injector can be told how to create objects using factories or it can try to create them itself using reflection. It can also be told to return an already-instantiated object when an interface is requested. Finally, if the requested interface has not been bound to a factory, implementation, or instance the injector will attempt to create the object using an implementation binder. For this to be successful the interface must actually be a concrete class.

Binders

The way we tell Horde_Injector how to create objects is using "binders" (which implement Horde_Injector_Binder). Horde_Injector maintains references to binders. References can be added in two ways:

$binder = new Horde_Injector_Binder_X($param1);
$injector->addBinder($interface, $binder)

$injector->bindX($interface, $param1);

Factory binders

[Factories|http://en.wikipedia.org/wiki/Factory_method_pattern] are classes with methods which instantiate and return objects. In the following example an interface is bound to a factory. If DataSourceX had dependencies it could instantiate them itself or ask $injector for those dependencies.

$injector->bindFactory('DataSourceInteface', 'DataSourceFactory', 'create');

class DataSourceFactory {
    public function create(Horde_Injector $injector) {
        return new DataSourceX();
    }
}

Factory method names can be whatever you want but they must only require one parameter and it must be a Horde_Injector object.

Implementation binders

Reflection allows us to programmatically inspect the structure of the class that is to be instantiated. By reading the interface types of the class constructor's parameters and then asking the injector to create those objects as well we try to provide the requested class's constructor with all its dependencies.

$injector->bindImplementation('DataSourceInteface', 'DataSourceX');

class DataSourceX {
    public function __construct(DependencyY $dependencyY) {
        ...
    }
}

Implementation binders also allow the calling of optional setter injection methods. Providing the method parameters here is done the same way as its done in the constructor, using reflection.

$injector->bindImplementation('DataSourceInteface', 'DataSourceX')
         ->bindSetter('setLogger');

class DataSourceX {
    public function __construct(DependencyY $dependencyY) {
        ...
    }

    public function setLogger(Logger $logger) {
        ...
    }
}

Choosing a binder

Use a factory binder if:

  • The class you are instantiating has any untyped parameters
  • You wish to create an instance of a class, that needs to have 2 objects of the same interface, but configured differently. [See FAQ|Dependency Injection Container FAQ]

Use an implementation binder if:

  • The class you are instantiating has only typed parameters

Instances

Horde_Injector maintains an array of object instances which are bound to interfaces. Instance binding happens two different ways: setting the instance binding manually, or by asking the injector to give you an instance (if it doesn't have one, then one is created and a reference to the internal instances array is added.)

$instance = new X();
$injector->setInstance('X', $instance);

Getting objects

For requested objects to be returned the injector must already have all the information present it needs to create the object.

Creating a new instance

To get a guaranteed new object use createInstance. References to instances retrieved in this manner are not stored. They will not be available to other objects unless you use setInstance to store the instance on the Injector.

$injector->createInstance('X');

Although the returned object will be new, its dependencies may not be. The injector will search its internal instances array for an instance matching the dependency's interface and if a match if found it will be used. If for some reason you need to guarantee that all dependencies are new, then you should consider using a factory binder.

Getting an instance

As previously mentioned instances are pooled by the injector, so getInstance() gives developers the opportunity to reuse objects. If an instance exists for the requested interface it will be returned, otherwise it will be created, added to the injectors internal instances array, and returned.

$injector->getInstance('X');

Scoping with child injectors

Horde_Injector implements the [Chain of Responsibility|http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern] design pattern with bindings and instances. What this means is that injectors will try to give you a binder or instance but if it doesn't have it it will ask its parent injector for them and try returning that to you.

$injector->bindFactory('InterfaceX', 'FactoryX', 'create');
$childInjector = $injector->createChildInjector();
$x = $childInjector->createInstance('InterfaceX'); // success!!!

$childInjector = $injector->createChildInjector();
$childInjector->bindFactory('InterfaceY', 'FactoryY', 'create');
$y = $injector->createInstance('InterfaceY'); // failure!!!

$x = $injector->getInstance('X');
$childInjector = $injector->createChildInjector();
$x === $childInjector->getInstance('X'); // true

Child Injectors allow you to configure sub-modules of code differently, without leaking any state into the global scope.