ZF3将全局配置的一部分注入服务工厂

时间:2016-09-03 20:58:27

标签: php factory zend-framework3

我在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中定义的配置并将其注入我的服务所需的工厂?

1 个答案:

答案 0 :(得分:1)

好的,经过一些调试和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']);
    }
}