【问题标题】:How can I use Zend\Di in Zend\ServiceManager in ZF2?如何在 ZF2 的 Zend\ServiceManager 中使用 Zend\Di?
【发布时间】:2012-11-10 18:52:17
【问题描述】:

我正在尝试让 Zend\ServiceManager 使用 Zend\Di 创建我的实例,因为我已经预先扫描和缓存了 DI 定义。我意识到这可能会降低速度,但另一方面,我需要编写更少的元代码。

ServiceManager documentation 这么说

ServiceManager 还提供与 Zend\Di 的可选联系,允许 Di 充当管理器的初始化器或抽象工厂。

但我没有找到任何关于如何让 ServiceManager 使用 Zend\Di 的示例。我什至不确定我应该在哪里设置它,也许在 Module::getServiceConfig() 中?谁能提供一些示例代码?

【问题讨论】:

标签: php dependency-injection zend-framework2


【解决方案1】:

以下内容对我有用。为了使 Zend\Di 与 Zend\ServiceManager 兼容,我从 Zend\Di\Di 扩展了一个 MyLib\Di\Di 类,它实现了 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);
    }
}

现在,我可以使用 MyLib\Di\Di 作为 Zend\ServiceManager 的备用抽象工厂。这是我如何创建 IndexController 的示例。 IndexController 的依赖项(构造函数参数)是自动注入的。

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');
                },
            ),
        );
    }
}

【讨论】:

    【解决方案2】:

    一个选项 - 添加到 config/module.config.php

    'service_manager' => array(
        'invokables' => array(
            'Application\Service\User'              => 'Application\Service\User',
        ),
      ),
    

    那么类需要实现 Zend\ServiceManager\ServiceManagerAwareInterface

    当启动时,serviceManager实例将被注入,然后你可以在类中使用这样的东西:

    $authService = $this->getServiceManager()->get('Zend\Authentication\AuthenticationService');
    

    第二种选择是将其放入 Module.php

    public function getServiceConfig()
    

    【讨论】:

    • 这不是如何使用Zend\DiZend\ServiceManager的答案
    • 好吧,您所描述的是 ZF2 beta 版本中不推荐使用的方式
    • 迪?不,它没有被弃用。除非您知道自己在做什么,否则不建议这样做。
    • 正如我所说,自测试版以来我没有使用过它。这就是为什么它在评论中而不是作为答案。我会问奥克拉米乌斯他是如何使用它的。
    猜你喜欢
    • 2023-03-23
    • 2015-03-10
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多