开发者

Automatically inject resources into controller

开发者 https://www.devze.com 2023-03-25 14:11 出处:网络
I\'m trying to implement dependency injection in our Zend Framework project. In previous APS.NET based projects we\'ve used StructureMap and overwritten theDefau开发者_运维技巧ltControllerFactory to

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 Defau开发者_运维技巧ltControllerFactory 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


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


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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号