4

我目前正在使用 ZF2 serviceManager,我试图弄清楚为什么 serviceManager 不会在实现 ServiceLocatorAwareInterface 的类中注入 sm。

我的主要问题是我做得对还是“服务”键不是用于实现 ServiceLocatorAwareInterface 的服务,而是用于不需要注入的服务?

在 Module.php 中

public function getServiceConfig() {
    return array(
        'invokables' => array(
            'myService1' => 'MyModule\Service\Service'
        ),
        'services' => array(
            'myService2' => new MyModule\Service\Service(),
        ),
    );
}

在 MyModule\Service\Service.php

namespace MyModule\Service;

use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;

class Service implements ServiceManagerAwareInterface
{
    /**
     * @var ServiceManager
     */
    protected $serviceManager = NULL;

    /**
     * Retrieve service manager instance
     *
     * @return ServiceManager
     */
    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set service manager instance
     *
     * @param ServiceManager $serviceManager
     */
    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
    }
}

当我在控制器中调用服务时

<?php

namespace MyModule\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{

    public function IndexAction() {

        $service1   = $this->getServiceLocator()->get('myService1');
        $sm1        = $service1->getServiceManager(); 
        //$sm1 becomes a object of Zend\ServiceManager\ServiceManager
        //In other words i now can access the SM from within my service.

        $service2   = $this->getServiceLocator()->get('myService2');
        $sm2        = $service2->getServiceManager(); 
        //$sm2 becomes NULL
        //The service isn't aware of the SM and can't access it.

    }

}
4

2 回答 2

5

如果您想使用 ServiceManagerAwareInterface 并将 Service Manager 自动注入到您的服务中,您应该继续使用“invokables”部分。

查看/Zend/ServiceManager/ServiceManager.php,“服务”意味着注册为已在 ServiceManager 中实例化的对象。当服务定位器在检索期间在其本地服务缓存中查找时,它假定“服务”已经完全设置并且不注入 sm 或运行任何初始化程序。

“invokables”、“factories”、“abstract_factories”是动态创建的,并在“initializers”在新创建的服务实例上运行时注入 sm(参见函数 create($name))。

于 2013-01-30T16:56:52.247 回答
3

忘记 getServiceConfig() 并改用您的模块配置。它更快且可缓存:

模块.config.php

'service_manager' => array(
    'invokables' => array(
        'MyModule\Service\Service' => 'MyModule\Service\Service',
    ),
)

MyModule\Service\Service.php

<?php
namespace MyModule\Service;

use \Zend\ServiceManager\ServiceLocatorInterface;

class Service
{
    public function __invoke(ServiceLocatorInterface $sm)
    {
        // go bananas here :)
    }

    public functiom greet()
    {
        return 'Hello World';
    }
}

zend2 内的任何地方

<?php
    $service=$serviceManager->get('MyModule\Service\Service');
    echo $service->greet();
于 2013-10-25T21:59:19.290 回答