Dependency Injection with PHP

Found this article while looking for an open source Dependency Injection engine for PHP.  The grammar needs a little work but otherwise it is a really good summary of what Dependency Injection is and why programmers should use it.

In ColdFusion we use ColdSpring which is based on the Spring Framework for Java.  It actually does a lot more than just DI but I am not concerned about that.  What I really want is something that can handle the same kind of DI situations that ColdSpring does for PHP.  I am currently working on a WordPress plugin for a freelance client which has turned out to be the most heavily object oriented PHP project I have done so far.  I have been trying to translate a lot the best practices I have learned while working with ColdFusion over to PHP and came across a need for DI.  What I ended up doing is creating a Factory that handles all of my object creation just like what is mentioned in the article by Ryan on PotStuck.  I pass an array with all of my classes, their paths, and their dependencies, like so:

$classes = array (
	'EventBean' => array (
		'path' => 'model/Event.php',
		'dependency' => array (
			'Venue' => 'VenueBean'
		)
	),
	'VenueBean' => array (
		'path' => 'model/Venue.php'
	)
);

So far it is working pretty well but I am thinking about making a more substantial DI framework that I can use on many projects to come.

Retweet

One Response to “Dependency Injection with PHP”

  1. Ryan says:

    Hi Aj,

    Thanks for the link to my blog about DI. I am actually working on a DI framework for php that should cover what you are looking for. I should be releasing it soon, just need to finish a few pieces.

    Also, grammar generally isn’t my strong point. If you notice any mistakes in my post feel free to point them out. The post needs a lot of updating since it is now over a year old!

    Ryan

Leave a Reply