PHP Dependency Injection
Dependency injection is the answer to more maintainable, testable, modular code.
Every project has dependencies and the more complex the project is the more dependencies it will most likely have. The most common dependency in today’s web application is the database and chances are if it goes down the app will all together stop working. That is because the code is dependent on the database server… and that is perfectly fine. Not using a database server because it could one day crash is a bit ridiculous. Even though the dependency has its flaws, it still makes life for the code, and thus the developer, a lot easier.
The problem with most dependencies its the way that code handles and interacts with them, meaning, the problem is the code and not the dependency. If you are not using dependency injection, chances are your code looks something like this:
class Book {
public function __construct() {
$registry = RegistrySingleton::getInstance();
$this->_databaseConnection = $registry->databaseConnection;
// or
global $databaseConnection;
$this->_databaseConnection = $databaseConnection;
}
}
The book object now is given full access to the database once it is constructed. That is good, the book needs to be able to talk to the database and pull data. The problem lies in the way the book gained its access. In order for the book to be able to talk to the database the code must have an outside variable named $databaseConnection, or worse, it must have a singleton pattern class (registry) object containing a record for a databaseConnection. If these don’t exist the book fails, making this code is far from modular.
This raises the question, how exactly does the book get access to the database? This is where inversion of control comes in.
In Hollywood a struggling actor does not call up Martin Scorsese and ask for a role in his next film. No, the opposite happens. Martin Scorsese calls up the broke actor and asks him to play the main character in his next movie. Objects are struggling actors, they do not get to pick the roles they play, the director needs to tell them what to do. Objects do not get to pick the outside systems they interact with, instead, the outside systems are given to the objects. Remember this as Inversion of Control: The Hollywood Way.
This is how a developer tells his objects how to interact with outside dependencies:
class Book {
public function __construct() { }
public function setDatabaseConnection($databaseConnection) {
$this->_databaseConnection = $databaseConnection;
}
}
$book = new Book(); $book->setDatabase($databaseConnection);
This code allows for the book class to be used in any web app. The Book is no longer dependent on anything other than the developer supplying a database shortly after object creation.
This is, at its finest, dependency injection. There are two common practices of injecting dependencies. The first being constructor injection and the second being setter injection. Constructor injection involves passing all of the dependencies as arguments when creating a new object. The code would look something like this:
$book = new Book($databaseConnection, $configFile);
The more dependencies an object has, the messier this construction becomes. There are other reasons why this is a bad approach, involving ideas around code reusability and constructors doing work.
This leaves us with other method of dependency injection, called setting injection, which involves creating a public method inside the object for the dependencies that need injection.
$book = new Book(); $book->setDatabase($databaseConnection); $book->setConfigFile($configFile);
This is easy to follow, but it leads writing more and more code for your application. When a book object is created three lines of code are required. If we have to inject another dependency, a 4th line of code is now needed. This gets messy quickly.
The answer to this problem is a factory, which is class that is designed to create and then inject all the dependencies needed for an object. Here is an example:
class Factory {
public static $_database;
public static function makeBook() {
$book = new Book();
$book->setDatabase(self::$_database);
// more injection...
return $book;
}
}
And then:
$book = Factory::makeBook();
All dependencies should be registered into the factory object during run time. This object is now the gateway that all dependencies must pass through before they can interact with any classes. In other words, this is the dependency container.
The reason makeBook is a public static function is for ease of use and global access. When I started this article off I made a reference to the singleton pattern and global access being a poor choices of code. They are… for the most part. It is bad design when they control access, but it is perfectly ok when they control creation. The makeBook function is only a shortcut for creation. There is no dependency what-so-ever between the book class and the factory class. The factory class exists so we can contain our dependencies in one location and automatically inject those dependencies with one line of code creation.
The factory or container class removes all of the extra work of dependency injection.
Before injection:
$book = new Book();
And now:
$book = Factory::makeBook();
Hardly any extra work, but tons of extra benefits.
When test code is run, specifically unit tests, the goal is to see if a method of a class is working correctly. Since the book class requires database access to read the book data it adds a whole layer of complexity. The test has to acquire a database connection, pull data, and test it. All of a sudden the test is no longer testing a single method in the book class, it is now also testing database. If the database is offline, the test would fail. This is FAR from the goal a unit test.
A way of dealing with this is just using a different database dependency for the unit tests. When the test suite starts up a dummy database is injected into the book. The dummy database will always have the data the developer expects it to have. If a live database was used in a unit test the data could potentially change causing tests to unnecessarily fail. There is no need for a unit test to be refactored when a record in a database changes.
The code is more modular because it can dropped into any other web application. Create the book object and inject a database connection with $book->setDatabase(). It does not matter if the database is in Registery::Database, $database, or $someRandomDatabaseVarible. As long as there is a database connection the book will work inside any system.
The code is more maintainable because each object given exactly what it needs. If separate database connections are required between different instances of the same class then there no extra code needed inside the class what-so-ever. Give book1 access to database1 and book2 access to database2.
Factory::$_database = $ourDatabaseVarForDB1; $book1 = Factory::makeBook(); $book2 = Factory::makeBook(); $book2->setDatabase($database2);
Dependency injection really is the answer to more maintainable, testable, modular code.
I titled this article PHP Dependency Injection, but there is really nothing in here that is specific to PHP. The reason I choose to include PHP and write all of the code examples in PHP is because I constantly see PHP projects not using DI. I believe the best place to teach good coding practices is in popular frameworks by forcing the users of the framework to develop within the guidelines of a certain pattern. Take MVC for example, now a days all developers understand it and most of the underlying principles that accompany it. This is because the frameworks they use force them to use MVC.
There was a proposal for a DI container to the Zend Framework. While in discussion on whether or not to include the container in the framework the proposal was shutdown due to its complexity and small benefit to the framework itself. Both were valid reasons to halt development. However, I do believe that if a container were to be shipped with the framework we would see better code written by it’s users. Better code leads to faster development time, which leads to feature filled projects, which then lead back to the framework, causing it to become more popular. I really would like to see more PHP developers using DI, and I do believe that the Zend Framework team has the ability to make that happen.
19 Comments
Huh?
Constructor injection is bad? Tell the Pico guys, the’ll be happy.
If a constructor gets too crowded, then you probably have a design problem.
The problem with setter inejction is: you have to know what to set and if you forget something it would not work, often violating the whole object principle.
Setter injection is good for optinal stuff, constructor for the required.
Also having a constructor with five parameters or calling five setters make no big difference.
In both cases it’s too much
i believe that no work should be done in your constructor, not even injection, so i am against it. code should be reusable and constructor code is not.
the problem with constructor injection, in my eyes, is that it can only be done upon object creation and it can only be done once. this becomes troublesome when you are caching objects that have references to resource types (db connection, etc). reinjecting via a setter eliminates this problem. its allows for reusable code, which is going to make development life easier.
i agree that 5 dependencies is way too much and bad. this was probably a bad example in my original piece. however, when dealing with multiple dependencies, setter injection is going to make the code more readable.
tbh, i have no real problem with constructor injection. all of the respected di frameworks support it. i do think that when someone is leaning di that it is better to push setter injection down their throat, but they should also be made aware of how constructor injection works.
thanks for the comments.
wow this blog does a great job of spacing paragraphs
Don and Ryan….great comments. Your comments show that both types of injection have their place, and DI frameworks should support both types. My soapbox: As a general rule of thumb, constructor injection should be limited to those dependencies that MUST be “set” before your object will work properly. Other dependencies can be done through setters, especially the dynamic ones as Ryan said. I’ve been working on an older Java codebase that uses the precursor to Spring (called interface21) that doesn’t have constructor injection. It would have helped with overall testability and design, especially.
[...] den letzten Monaten wurden in einigen Blogs immer mal wieder Beiträge zum Thema Dependency Injection (DI) in PHP verfasst. In einem aktuellen Beitrag von Fabien Potencier, dem [...]
One thing I think that Don doesn’t realise (or maybe forgot to mention) is that constructor-based setting of dependencies makes unit testing more difficult, as you can’t mock out a constructor. I much rather use a setter method externally to create dependencies, as it makes your tests easier to write and as Ryan stated, makes it more readable – as you know exactly what’s going on without having to look inside the class.
Good Stuff
I’d say worth mentioning this;
http://martinfowler.com/articles/injection.html
“My long running default with objects is as much as possible, to create valid objects at construction time.
…
Despite the disadvantages my preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I’ve outlined above start to become a problem.”
Nice article
…
…
I agree to the point mentioned by Kirk and to take care of the must set attributes issue, you can always have constructor injection together with setter injection and a private constructor with methods that would provide you ways of creating a fully functional object v/s a mock object.
I believe that design patterns are there primarily to make code management easier. Sticking with some pattern does not always solve the problem of code maintenance and scalability.
Hi there!
I’d be happy if you could tell me which plugin you use to highlight your sourcecode!
simon
simon,
i am using google syntax highlighter
http://code.google.com/p/syntaxhighlighter/
Hi,
For the setter/constructor dilema, here is a possible solution (Misko Hevery):
* Constructor injection: injected class lifetime >= class lifetime
* Setter injection: injected class lifetime <= class lifetime
That way, the problems you discribe does not occur.
[...] else that we’ll do in order to improve testability is we will inject (rather than create) the HTTPRequest object into the class. This allows us to both inject an object [...]
I understand what’s going on with DI, except this. In the example of using setter injection, Ryan mentioned creating two Book objects. Book1 would have access to database1, and Book2 would have access to database2. There is one lingering question in my mind…
So, database1 and database2 are required to have the same interface? For instance, if you wanted to perform a query on database1, you might call a performQuery() function for retrieving data. With database2, the proper function might be executeQuery(). So, injecting dependencies forces rigid interface standards on the objects that are depended upon?
Or am I totally off base?
Dave,
The idea is that database1 and database2 are both the same class, but different objects (instances). We are not trying to write code that will fit with any interface, we only want to work with our interface.
The reason we inject the different databases is because sometimes we are using a production database to pull real data, and other times we are using a mock database to test our code.
Injection leaves it up to US, not the class, to decide which database to use. This gives us much greater long term flexibility as well as makes our objects loosely coupled.
[...] I do not know about dependency injection – do you have any links that do not require subscription? I’ll talk about Dependency Injection here. It’s actually a really simple topic. [...]
Very useful, thanks.
Thanks for sharing this. I found a mention of Dependency Injection on Brandon Savage’s PHP blog; but this explains it.
[...] who do the work are dumb; instead, the departments themselves are dependent on you giving them (dependency injection) the proper [...]
Dave,
If you want to using database with different interface you can inject into the Book a data mapper object (http://martinfowler.com/eaaCatalog/dataMapper.html) instead the Database object.