gpt4 book ai didi

php - 为什么将 Servicemanager 注入(inject)可调用而不是服务

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:09:08 28 4
gpt4 key购买 nike

我目前正在使用 ZF2 serviceManager,我试图弄清楚为什么 serviceManager 没有将 sm 注入(inject)到实现 ServiceLocatorAwareInterface 的类中。

我的主要问题是我做对了吗?或者“服务”键不是用于实现 ServiceLocatorAwareInterface 的服务,而是用于不需要注入(inject)的服务?

在 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;
}
}

当我在 Controller 中调用服务时

<?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.

}

}

最佳答案

如果您想使用 ServiceManagerAwareInterface 并将服务管理器自动注入(inject)到您的服务中,您应该继续使用“可调用”部分。

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

“invokables”、“factories”、“abstract_factories”是动态创建的,并在“初始化程序”在新创建的服务实例上运行时注入(inject) sm(请参阅函数 create($name))。

关于php - 为什么将 Servicemanager 注入(inject)可调用而不是服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14608850/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com