ZF2 初始化器和 TranslatorAwareInterface

ZF2 initializers and TranslatorAwareInterface

我认为这是一个简单的问题。

ZF2 的 ServiceManager 如果某些接口在 class 中实现,则可以自动注入依赖项,即。 ServiceLocatorAwareInterfaceEventManagerAwareInterface

我的问题是:为什么在我执行 TranslatorAwareInterface 时它不注入翻译器?

发生这种情况是因为 ZF2 ServiceManager 配置对实现 ServiceManagerAwareInterfaceServiceLocatorAwareInterface.

的服务有默认的 initializers

您可以在 __construct method of the ServiceManagerConfig 中找到 ServiceManagerAwareInitializerServiceLocatorAwareInitializer

要为您自己的界面实现此功能,您必须注册自己的界面 initializer。这里有一个关于如何为翻译人员执行此操作的示例:

'service_manager' => array(
    'invokables' => array(
        //...
    ),
    'factories' => array(
        //...
        'translator' => 'My\Factory\TranslatorFactory'
    ),
    'initializers' => array(
        // Inject translator into TranslatorAwareInterface
        'translator' => function($service, ServiceLocatorInterface $serviceLocator) {
            if ($service instanceof TranslatorAwareInterface) {
                $translator = $serviceLocator->get('translator');
                $service->setTranslator($translator);
            }
        }
    )
)

您必须确保在 serviceManager 中将您的译员注册为 translator 才能完成这项工作。我用 My\Factory\TranslatorFactory.

创建了它

ZF2 documentation for the ServiceManager 中阅读有关 initializers 的更多信息。

请注意,对于您创建的每个服务,initializer 将检查它是否需要注入您的依赖项。