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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!