3

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

ServiceManager文档

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

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

4

2 回答 2

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');
                },
            ),
        );
    }
}
于 2012-11-26T12:47:16.707 回答
-1

一种选择 - 添加到 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()
于 2012-11-22T23:59:43.170 回答