Following on from our recent article on writing testable PHP code, it seems sensible to point out Ian Barber’s article on dependency injection for Zend Framework controllers over at the iBuildings site.
The article outlines three approaches to injecting objects into your controllers. The first is via the Zend_Registry object, which should not be your preferred technique. Zend_Registry is just an over hyped singleton object and a perfect way of adding the dreaded global state to your application. Also, with this technique you mitigate and dependancy on your chosen objects for a dependency on the registry object itself, so your classes are still tightly coupled in a way.
The second technique is via Zend_Controller_Front params. This has the benefit of decoupling your objects but still feels a little clunky in practice.
The third and most interesting technique is to inject your objects via an action helper. This technique works by taking advantage of the action helpers hooks into the dispatch loop. It’s rather neat and provides a complete decoupling of your objects.
<?php
/**
* An action helper for injecting objects
*/
class MyApp_Helpers_SomeObjectInjector extends Zend_Controller_Action_Helper_Abstract {
protected $_someObject;
public function init() {
$this->_someObject = new MyApp_SomeObject();
}
public function preDispatch() {
$this->getActionController()->setSomeObject($this->_someObject);
}
}
?>
You can then set this up as a helper in your bootstrap file so it gets hooked into the dispatch loop. Of course your controller will also need the method setSomeObject().
<?php
Zend_Controller_Action_HelperBroker::addHelper(new MyApp_Helpers_SomeObjectInjector());
?>
Whilst this method is one of the neatest I’ve found so far it does still seem a little hacky. Some of the comments on the original post raise the question of a need for a proper dependency injection container in the framework.
Comment
blog comments powered by Disqus