ZF3 将部分全局配置注入服务工厂
ZF3 Inject part of global config into a service factory
我在 Module.php
中定义了一项服务,我在其中注入 mail
配置,在 config/autoload/global.php
中以这种方式定义:
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
'Mailer' => function($container) {
return new MailService($this->getConfig()['mail']);
},
]
];
}
但我想用 ZF3 的方式来做(我正在学习,所以我在我的 module.config.php
中定义了我的服务:
return [
'services' => [
'factories' => [
Service\MailService::class => MailServiceFactory::class
]
],
我的 MailServiceFactory.php
是:
class MailServiceFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new MailService();
}
}
但是我怎样才能检索我在 global.php
中定义的配置并将其注入我的服务所需的工厂?
好的,经过一些调试和 var_dump()
,我有了它。感谢 $container->get('configuration')
,我可以访问配置数组。所以我的工厂现在是:
class MailServiceFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('configuration');
return new MailService($config['mail']);
}
}
我在 Module.php
中定义了一项服务,我在其中注入 mail
配置,在 config/autoload/global.php
中以这种方式定义:
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
'Mailer' => function($container) {
return new MailService($this->getConfig()['mail']);
},
]
];
}
但我想用 ZF3 的方式来做(我正在学习,所以我在我的 module.config.php
中定义了我的服务:
return [
'services' => [
'factories' => [
Service\MailService::class => MailServiceFactory::class
]
],
我的 MailServiceFactory.php
是:
class MailServiceFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new MailService();
}
}
但是我怎样才能检索我在 global.php
中定义的配置并将其注入我的服务所需的工厂?
好的,经过一些调试和 var_dump()
,我有了它。感谢 $container->get('configuration')
,我可以访问配置数组。所以我的工厂现在是:
class MailServiceFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('configuration');
return new MailService($config['mail']);
}
}