dongxinpa3101 2012-11-22 11:18
浏览 66
已采纳

如何在ZF2中的Zend \ ServiceManager中使用Zend \ Di?

I'm trying to make the Zend\ServiceManager use Zend\Di to create my instances, since I have pre-scanned and cached DI definitions already. I realize this might come with a speed penalty but on the other hand, I need to write a lot less meta-code.

The ServiceManager documentation says that

the ServiceManager also provides optional ties to Zend\Di, allowing Di to act as an initializer or an abstract factory for the manager.

But I don't find any examples of how make the ServiceManager use Zend\Di. I'm not even sure where I should set this up, maybe in Module::getServiceConfig()? Can anyone provide some example code?

  • 写回答

2条回答 默认 最新

  • duanba7498 2012-11-26 12:47
    关注

    The following works for me. In order to make Zend\Di compatible with Zend\ServiceManager, I extended a class MyLib\Di\Di from Zend\Di\Di which implements the AbstractFactoryInterface.

    namespace MyLib\Di;
    use Zend\ServiceManager\AbstractFactoryInterface; 
    use Zend\ServiceManager\ServiceLocatorInterface;
    
    class Di extends \Zend\Di\Di implements AbstractFactoryInterface
    {
        public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
        {
            return true;
        }
    
        public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
        {
            return $this->get($requestedName);
        }
    }
    

    Now, I can use MyLib\Di\Di as a fallback abstract factory for Zend\ServiceManager. Here's an example of how I create my IndexController. The IndexController's dependencies (constructor parameters) are injected automatically.

    class Module
    {
        ... 
    
        public function getServiceConfig()
        {        
            $this->di = new \MyLib\Di\Di;
            $this->configureDi($this->di); // Set up definitions and shared instances
    
            return array(
                'abstract_factories' => array($this->di),
            );
        }
    
        public function getControllerConfig()
        {
            return array(
                'factories' => array(
                    'Survey\Controller\IndexController' => function() {
                        return $this->di->get('Survey\Controller\IndexController');
                    },
                ),
            );
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证