LordMagik
LordMagik

Reputation: 43

Why to use Dependency Injection components in PHP frameworks

When I first saw dependency injection components like PHP-DI, Symfony2 DI, etc., I though, there is a way to automatically inject instance of any class to any just with one instantiation.

So 1. Create instance in root class like $foo = new Foo() 2. And then I can use this instance in any object (like global singleton) without passing reference to constructor or method of the class I want to call from.

But I found out, that basicly I can use Dependency Injection in 2 ways 1. Passing the reference of the instance to constructor 2. Creating container where all objects are located. This container could be injected to other classes, but "This is not recommended".

As both ways can be easily done in pure PHP, the first is clear, the second could be solved with static properties, so why to use PHP-DI or Symfony2 for this work?

Upvotes: 2

Views: 369

Answers (1)

hanzi
hanzi

Reputation: 2987

Why should you use Dependency Injection over the Singleton pattern?

Let's assume we have a Singleton object named DatabaseConnection which wraps a connection to a MySQL database for us and does some other neat things, who knows. Because reusing code is a good thing, we use this object in a lot of projects.

What if at some point we decide to switch one of our projects from MySQL to another database product? We would have to modify every place where we call the DatabaseConnection object and replace it with our new implementation. Or, we could modify the class itself -- but we still want to use the original one with other projects, so we end up with two implementations with the same name which is just asking for trouble, really.

And what about unit tests? We do those, of course, because we are good developers! But if we unit test a function that uses the database, we don't want the test to actually rely on the database or even change things there. There's no way to replace the DatabaseConnection with a mock object (that just returns static data) because our project is tightly coupled to it.

That's what Dependency Injection does: It helps to prevent tight coupling. If we inject the connection with $someObject->setDatabaseConnection($databaseConnection), we can inject any object there that behaves like the original one. We can inject mock objects, alternative implementations or extensions that inherit the original class.

Now a Dependency Injection Container is just a nice helper to manage object instances and their dependencies more easily, but it's not needed for doing Dependency Injection.

Upvotes: 2

Related Questions