How to use dependency injection in Zend Framework?

bredaboy90

New Member
Currently I am trying to learn the Zend Framework and therefore I bought the book "Zend Framework in Action". In chapter 3, a basic model and controller is introduced along with unit tests for both of them. The basic controller looks like this:\[code\]class IndexController extends Zend_Controller_Action { public function indexAction() { $this->view->title = 'Welcome'; $placesFinder = new Places(); $this->view->places = $placesFinder->fetchLatest(); }}\[/code\]\[code\]Places\[/code\] is the model class that fetches the latest places from the database. What bugs me here: how should I test the \[code\]IndexController\[/code\] in isolation? As the reference to the \[code\]Places\[/code\] class is "hardcoded", I cant inject any stubs or mocks in \[code\]IndexController\[/code\].What I would rather like to have is something like this:\[code\]class IndexController extends Zend_Controller_Action { private $placesFinder; // Here I can inject anything: mock, stub, the real instance public function setPlacesFinder($places) { $this->placesFinder = $places; } public function indexAction() { $this->view->title = 'Welcome'; $this->view->places = $this->placesFinder->fetchLatest(); }}\[/code\]The first code sample I posted is most definately NOT unit test friendly as \[code\]IndexController\[/code\] cannot be tested in isolation. The second one is much better. Now I just need some way to inject the model instances into the controller objects.I know that the Zend Framework per se has no component for dependency injection. But there are some good frameworks out there for PHP, can any be used together with Zend Framework? Or is there some other way to do this in Zend Framework?
 
Back
Top