Initializers ZF2 and TranslatorAwareInterface

I think this is a simple question.

ZF2 ServiceManagercan automatically enter dependencies if certain interfaces are implemented in the class, i.e. ServiceLocatorAwareInterfaceor EventManagerAwareInterface.

My question is: why doesn't he introduce a translator when I implement TranslatorAwareInterface?

+4
source share
1 answer

This is because, for configuration, ZF2 ServiceManageris used by default initializersfor services that implement ServiceManagerAwareInterfaceor ServiceLocatorAwareInterface.

You can find ServiceManagerAwareInitializer, and ServiceLocatorAwareInitializerin the method . __constructServiceManagerConfig

, 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);
            }
        }
    )
)

, translator ServiceManager, . My\Factory\TranslatorFactory.

initializers ZF2 ServiceManager.

, initializer , .

+4

All Articles