Php ZF2初始值设定项和TranslatorAwareInterface

Php ZF2初始值设定项和TranslatorAwareInterface,php,zend-framework,zend-framework2,Php,Zend Framework,Zend Framework2,我认为这是一个简单的问题 如果某些接口在类中实现,则ZF2的ServiceManager可以自动注入依赖项,即ServiceLocatorAwareInterface或EventManagerAwareInterface 我的问题是:为什么在我实现TranslatorAwareInterface时它不注入转换器?这是因为ZF2ServiceManager配置为实现ServiceManagerAwareInterface或ServiceLocatorAwareInterface的服务提供了默认的初

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

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


我的问题是:为什么在我实现
TranslatorAwareInterface
时它不注入转换器?

这是因为ZF2
ServiceManager
配置为实现
ServiceManagerAwareInterface
ServiceLocatorAwareInterface
的服务提供了默认的
初始值设定项

您可以在中找到
ServiceManagerAwareInitializer
ServiceLocatorAwareInitializer

要为自己的接口实现这一点,您必须注册自己的
初始值设定项。下面是一个关于如何为翻译人员执行此操作的示例:

'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
创建了它

阅读中有关初始化器的更多信息


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

您如何实例化该类?通过调用$serviceman->get('class'),这将调用该类的工厂。我认为zf2默认使用此初始值设定项,出于某种原因,他们删除了它: