Reputation: 1512
I'm trying to implement dependency injection in our Zend Framework project.
In previous APS.NET based projects we've used StructureMap and overwritten the DefaultControllerFactory
to inject the dependencies into the controllers.
I'm not sure where to do the injection in Zend Framework? I've looked into Zend_Controller_Plugin_Abstract
and Zend_Controller_Action_Helper_Abstract
but none of them seems to enable me to inject into the currently instantiated controller.
I would love to be able to inject into the constructor of the current controller like i do in ASP.NET, but setters are acceptable (I guess).
Any ideas as to how to accomplish this or something similar?
Ultimately i would like to be able to do something like this:
MyController extends Zend_Controller_Action {
// private vars
[...]
public function __constructor($authenticationService, $userRepository) {
$this->_authServ = $authenticationService;
$this->_userRepo = $userRepository;
}
}
I would like to do something like i do for stuctureMap:
For(authenticationService).Use(WhatEverClass);
or maybe:
$currentController->authServ = $authenticationService;
$currentController->userRepo = $userRepository;
In short: Where can we intercept the creation of (or get the instance of) the current controller?
Similar (unanswered) question here
Thanks! /Jon
Upvotes: 3
Views: 284
Reputation: 49623
Check out also PHP-DI, this is a dependency injection library that integrates with Zend Framework. It works with annotations.
It enables you to do things like:
MyController extends Zend_Controller_Action {
/**
* @Inject
* @var MyService
*/
private $myService;
public function helloAction() {
return $this->myService->sayHello();
}
}
Upvotes: 1
Reputation: 14184
Zend Framework lead developer Matthew Weier O'Phinney has a post that seems to address the idea of injecting resources into controllers:
A Simple Resource Injector for ZF Action Controllers
Upvotes: 4