Dependency Injection with PHP

Since Java is a little more static than PHP from a language construct standpoint, the Java Community have adopted the concept of Dependency Injection (DI) a couple of years ago (for example in the Spring framework). Now PHP is getting more mature and people are wondering how to best decouple components in big projects in order to prevent interdependencies. Originally coming from the Java world, i found DI very interesting from the beginning on.

When i contributed my first (and only) code to Zend Framework, i tried to use dependency injection there. This is why you can still "inject" a Zend_Mail_Transport object to Zend_Mail when you want to send the email out:

$mail = new Zend_Mail(...);
...
$trans = new MyTransport(<arbitrary config options for my transport>);
$mail->send($trans);

But it seemed like this concept was not very popular in the PHP community. Obviously the more common approach to define which driver to use for a given Functionality is to make factory methods that take associative arrays as parameters:

$db = Zend_Db::factory('Pdo_Mysql', array(
    'host'     => '127.0.0.1',
    'username' => 'webuser',
    'password' => 'xxxxxxxx',
    'dbname'   => 'test'
));

These days, there seems to be a new movement in the PHP community to evaluate DI. On the international PHP conference in Karlsruhe, Fabien Potencier has made an excellent presentation about how DI can help you in PHP and how to implement a container that helps to get most benefit out of it. Since i still like the concept of DI, i am very curious on how this develops further. DI: I love it!

Auf Facebook teilen

« Upgrading to VMWare Player 3.0 on Ubuntu 9.10 - Toshiba Portege R500 and Win7 »