如何在 zend 框架 3 (zf3) 的工厂中检索应用程序配置值?

How to retrieve application config values in factories in zend framework 3 (zf3)?

我可以通过

在工厂中检索配置
class MyControllerFactory implements FactoryInterface{

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {   
        $config = $container->get('Config') ;
    }
}

但这不包含我在 application.config.php. 中配置的内容 我如何访问 zf3 中的 application.config 设置数组?

来自 application.config.php 的配置在 ApplicationConfig 服务密钥下注册,该服务密钥在使用默认行为初始化 ZF3 应用程序时注册。因此,在工厂方法中使用以下代码片段:

$configuration   = $container->get('ApplicationConfig');

这是为了澄清

在 ZF3 中,如果您正在创建应用程序中需要的任何 类,请使它们可服务,通过 ServiceManager 使它们在您的应用程序中可用。 ServiceManager 实现了一个存储注册服务的容器。怎么样? ZF 使用一种称为工厂的方法(简而言之,它创建对象)。它有助于将服务存储到容器中。然后我们可以使用 ServiceManager 从该容器中提取服务。让我们看看如何?

ServiceManager 本身就是一个服务。

因此,使用工厂让我们在控制器(例如 IndexController)中提供 ServiceManager 实例。这样我们就可以使用它获得任何服务。

Application\Controller\IndexControllerFactory

<?php
    namespace Application\Controller;

    // This is the container 
    use Interop\Container\ContainerInterface;
    use Zend\ServiceManager\Factory\FactoryInterface;

    class IndexControllerFactory implements FactoryInterface
    {
        public function __invoke(ContainerInterface $container, $requestedName, array $options = NULL)
        {   
           $serviceManager = $container->get('ServiceManager');
           return new IndexController($serviceManager);
        }    
     }

让我们配置它以便我们可以使用它。在 moudle.config.php

中进行以下更改
'controllers' => [
    'factories' => [
        Controller\IndexController::class =>    Controller\IndexControllerFactory::class,
    ],
 ],

一旦 IndexControllerFactory 实例化了 IndexController(通过上述配置),ServiceManager 实例就可以通过 IndexController 的构造函数使用。