ZF2 使用 MutableCreationOptionsTrait 从工厂实例化 classes:无论如何创建相同的 class 实例

ZF2 instantiating classes from factories using MutableCreationOptionsTrait: creates the same instance of class no matter what

在ZF2中,我有一个这样的工厂

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 是完全相同的对象,而它应该具有不同的依赖关系。我试着研究了一下这个东西,似乎 $creationOptions 在分配 $service2 时没有更新,尽管 valueType 是完全不同的。

怎么了?

不小心在评论中遇到了以下问题的答案(@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,
    ],
],

http://framework.zend.com/manual/current/en/modules/zend.service-manager.quick-start.html#sample-configuration