\documentclass{article}
\usepackage{ulem}
\usepackage{graphicx}
\usepackage{hyperref}
\pagestyle{headings}
\begin{document}
\part{Introduction}
The dependency injection pattern (<a href="http://en.wikipedia.org/wiki/Dependency\_injection\">http://en.wikipedia.org/wiki/Dependency\textbackslash\{\}\_injection\textbackslash\{\}</a>) 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<br />
dependencies between different code modules. Another major benefit of dependency injection is the fact that it facilitates unit testing of complex systems.

\part{Horde\_Injector}
Horde\_Injector provides a "Dependency Injection" framework.  For PHP there exist several dependency injection frameworks (e.g. <a href="http://stubbles.net">http://stubbles.net</a>, <a href="http://components.symfony-project.org/dependency-injection\">http://components.symfony-project.org/dependency-injection\textbackslash\{\}</a>) 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 (<a href="http://twittee.org/\">http://twittee.org/\textbackslash\{\}</a>). 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.

\section{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 \textbf{not}

\begin{itemize}
\item pull in a dependency using global state via the singleton pattern:


\end{itemize}
<pre><code class="language-php">
External\_Class::singleton();
</code></pre>
\begin{itemize}
\item create new objects with dependencies:


\end{itemize}
<pre><code class="language-php">
\$db = new DB();
\$b = new User(\$db);
</code></pre>
\begin{itemize}
\item use global variables:


\end{itemize}
<pre><code class="language-php">
global \$conf;
\$db = new DB(\$conf['sql');
</code></pre>
In most cases the class should receive dependencies and required parameters within the constructor.

\section{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:

<pre><code class="language-php">
\$a = new Horde\_Injector(new Horde\_Injector\_TopLevel());
\$a->setInstance('a', 'a');
echo \$a->getInstance('a');
</code></pre>
<pre><code>
string(1) "a"
</code></pre>
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:

<pre><code class="language-php">
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'));
</code></pre>
<pre><code>
string(11) "constructed"
</code></pre>
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<br />
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.

\subsection{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:

<pre><code class="language-php">
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();
</code></pre>
<pre><code>
Hello Bob
</code></pre>
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:

<pre><code class="language-php">
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();
</code></pre>
<pre><code>
Hello World
</code></pre>
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.

\section{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:

<pre><code class="language-php">
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']);
    \}
\}
</code></pre>
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:

<pre><code>
    /**
     * Constructor.
     *
     * @param DB \$db A database connection.
     */
    public function \_\_construct(DB \$db)
    \{
        \$this->\_db = \$db;
    \}
</code></pre>
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.

\subsection{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:

<pre><code class="language-php">
    static public function singleton()
    \{
        if (!isset(self::\$\_instance)) \{
            global \$conf;

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

        return self::\$\_instance;
    \}
</code></pre>
The final result that can be used with a dependency injection framework and still provides a backward compatible singleton method:

<pre><code class="language-php">
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;
    \}
\}
</code></pre>
\section{Dependency Injection Container FAQ}
\subsection{Where can \texttt{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.

\subsection{How do I provide \texttt{Horde\_Config} values to my business models?}
Factories.

<pre><code class="language-php">
\$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);
    \}
\}
</code></pre>
\subsection{I have an \texttt{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 <a href="https://wiki.horde.org/ArrayObject">ArrayObject</a> is used. Does this array get reused? If so it may be worth creating a special extension of <a href="https://wiki.horde.org/ArrayObject">ArrayObject</a>.

<pre><code class="language-php">
\$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')
        ));
    \}
\}
</code></pre>
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 \texttt{Logger}. If you have defined a factory for your \texttt{Dictionary} object, then you must edit that factory and create a \texttt{Logger} and pass it to your \texttt{Dictionary}. With the method above, you would simply need to edit your constructor, and the \texttt{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.

\section{Dependency Injection Container Spec}

\noindent\rule{\textwidth}{1pt}
\subsection{Terms}
\begin{itemize}
\item Dependency Injection - DI


\item Dependency Injection Container - DIC


\end{itemize}

\noindent\rule{\textwidth}{1pt}
\subsection{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.


\noindent\rule{\textwidth}{1pt}
\subsection{Functional Spec}
\subsubsection{Goals}
\begin{itemize}
\item Decouple application layer (controller) from business layer (model)


\item Allow easy use of models which are decoupled from their dependencies using DI


\item Favor code over configuration


\item Simple, testable design


\end{itemize}
\subsubsection{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.


\noindent\rule{\textwidth}{1pt}
\subsection{Technical Spec}
The name of our DIC implementation is \texttt{Horde\_Injector}. \texttt{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.

\subsection{Binders}
The way we tell \texttt{Horde\_Injector} how to create objects is using "binders" (which implement \texttt{Horde\_Injector\_Binder}). \texttt{Horde\_Injector} maintains references to binders. References can be added in two ways:

<pre><code class="language-php">
\$binder = new Horde\_Injector\_Binder\_X(\$param1);
\$injector->addBinder(\$interface, \$binder)
</code></pre>
<pre><code class="language-php">
\$injector->bindX(\$interface, \$param1);
</code></pre>
\paragraph{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 \texttt{[DataSourceX](DataSourceX)} had dependencies it could instantiate them itself or ask \texttt{\$injector} for those dependencies.

<pre><code class="language-php">
\$injector->bindFactory('DataSourceInteface', 'DataSourceFactory', 'create');

class DataSourceFactory \{
    public function create(Horde\_Injector \$injector) \{
        return new DataSourceX();
    \}
\}
</code></pre>
\textit{Factory method names can be whatever you want but they must only require one parameter and it must be a \texttt{Horde\_Injector} object.}

\paragraph{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.

<pre><code class="language-php">
\$injector->bindImplementation('DataSourceInteface', 'DataSourceX');

class DataSourceX \{
    public function \_\_construct(DependencyY \$dependencyY) \{
        ...
    \}
\}
</code></pre>
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.

<pre><code class="language-php">
\$injector->bindImplementation('DataSourceInteface', 'DataSourceX')
         ->bindSetter('setLogger');

class DataSourceX \{
    public function \_\_construct(DependencyY \$dependencyY) \{
        ...
    \}

    public function setLogger(Logger \$logger) \{
        ...
    \}
\}
</code></pre>
\paragraph{Choosing a binder}
Use a factory binder if:

\begin{itemize}
\item The class you are instantiating has any untyped parameters


\item You wish to create an instance of a class, that needs to have 2 objects of the same interface, but configured differently. <a href="https://wiki.horde.org/See">FAQ|Dependency Injection Container FAQ</a>


\end{itemize}
Use an implementation binder if:

\begin{itemize}
\item The class you are instantiating has only typed parameters


\end{itemize}
\subsubsection{Instances}
\texttt{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.)

<pre><code class="language-php">
\$instance = new X();
\$injector->setInstance('X', \$instance);
</code></pre>
\subsubsection{Getting objects}
For requested objects to be returned the injector must already have all the information present it needs to create the object.

\paragraph{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 \texttt{setInstance} to store the instance on the Injector.

<pre><code class="language-php">
\$injector->createInstance('X');
</code></pre>
\textit{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.}

\paragraph{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.

<pre><code class="language-php">
\$injector->getInstance('X');
</code></pre>
\subsubsection{Scoping with child injectors}
\texttt{Horde\_Injector} implements the <a href="https://wiki.horde.org/Chain">of Responsibility|http://en.wikipedia.org/wiki/Chain-of-responsibility\_pattern</a> 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.

<pre><code class="language-php">
\$injector->bindFactory('InterfaceX', 'FactoryX', 'create');
\$childInjector = \$injector->createChildInjector();
\$x = \$childInjector->createInstance('InterfaceX'); // success!!!
</code></pre>
<pre><code class="language-php">
\$childInjector = \$injector->createChildInjector();
\$childInjector->bindFactory('InterfaceY', 'FactoryY', 'create');
\$y = \$injector->createInstance('InterfaceY'); // failure!!!
</code></pre>
<pre><code class="language-php">
\$x = \$injector->getInstance('X');
\$childInjector = \$injector->createChildInjector();
\$x === \$childInjector->getInstance('X'); // true
</code></pre>
Child Injectors allow you to configure sub-modules of code differently, without leaking any state into the global scope.

\end{document}
