Zend framework ZF2使用MutableCreationOptions从工厂实例化类:不管发生什么情况,都会创建相同的类实例
在ZF2中,我有一个这样的工厂Zend framework ZF2使用MutableCreationOptions从工厂实例化类:不管发生什么情况,都会创建相同的类实例,zend-framework,zend-framework2,Zend Framework,Zend Framework2,在ZF2中,我有一个这样的工厂 class SomeServiceFactory implements FactoryInterface, MutableCreationOptionsInterface { use MutableCreationOptionsTrait; public function createService(ServiceLocatorInterface $serviceLocator) { $serviceManager = $
class SomeServiceFactory implements FactoryInterface, MutableCreationOptionsInterface
{
use MutableCreationOptionsTrait;
public function createService(ServiceLocatorInterface $serviceLocator)
{
$serviceManager = $serviceLocator->getServiceLocator();
$formElementManager = $serviceManager->get('FormElementManager');
if ($this->creationOptions == 'value1') {
return new SomeService(
$formElementManager->get('Path\To\Form1'),
$serviceManager->get('Path\To\Mapper1'),
new Object1()
);
} elseif ($this->creationOptions == 'value2') {
return new SomeService(
$formElementManager->get('Path\To\Form2'),
$serviceManager->get('Path\to\Mapper2'),
new Object2()
);
}
}
}
在控制器工厂中,我根据对象创建时附加的选项值获得了几个SomeService
实例,如
$service1 = $viewHelperManager->get('Path\To\SomeService', ['valueType' => 'value1']);
$service2 = $viewHelperManager->get('Path\To\SomeService', ['valueType' => 'value2']);
(这些服务是视图帮助程序及其依赖项)
问题在于$service2
与$service1
是完全相同的对象,但它应该具有不同的依赖关系。我试着研究一下这个问题,似乎在分配$service2
时,$creationOptions
没有更新,尽管值类型
完全不同
怎么了?不小心碰到了以下问题评论中的答案(@AlexP,如果你能听到我的话,谢谢你,伙计!): 默认情况下,ZF2共享服务。如果您想在每次调用工厂时创建新服务,则需要在
module.confing.php
的相应项下指定shared
指令,如下所示:
'view_helpers' => [
'factories' => [
// some factories including the name of the one that
// you don't want to create new instances each time it's called
],
'shared' => [
'Alias\Of\That\Factory' => false,
],
],