ZendFramework2:是否可以在没有 serviceLocator 的情况下将 global.php 配置到模型中?

ZendFramework2: Is it possible to get global.php config into a model without serviceLocator?

在 config/autoload/global.php 中,我只有数据库的配置。 在我的模型中,我有:

public function __construct($adapter = null)
    {
        if ($adapter) {
            $this->adapter = $adapter;
        } else {
            ... //here I need to get the config without serviceLocator  
        }
    }
public function attach(EventManagerInterface $events)
    {
        $sharedEvents = $events->getSharedManager();
        $this->listeners[] = $sharedEvents->attach("*", "redirect", array($this, "onRedirect"));
    }

    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener)
        {
            if ($events->detach($listener))
            {
                unset($this->listeners[$index]);
            }
        }
    }

    public function onRedirect(EventInterface $e)
    {
        ...
    }

原因很简单。我试图在触发事件时向数据库中添加一些内容,但我无法在侦听器上获取 serviceLocator。不知道为什么。

那么...是否可以在没有 serviceLocator 的情况下获取配置文件?

您应该能够像在任何其他服务中一样通过工厂在您的侦听器中获取 ServiceLocator

<?php

namespace Application\Listener\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Application\Listener\SomeListener;

/**
 * Factory for creating the listener
 */
class SomeListenerFactory implements FactoryInterface
{
    /**
     * Create SomeListener
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return SomeListener
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('config');
        $adapter = // create adapter using config and use it to create your listener
        return new SomeListener($adapter);
    }
}

在您的 module.config.php:

中注册您的侦听器工厂
'service_manager' => array(
    'factories' => array(
        'Application\Listener\SomeListener' => 'Application\Listener\Factory\SomeListenerFactory',
    )
)

现在您可以在任何您想要的地方从服务管理器获取监听器:

$someListener = $serviceManager->get('Application\Listener\SomeListener');

如果你真的想在你的 class 中进行配置(我看不出有任何必要这样做的原因并且它违反了 ZF2 原则)你可以包含你的配置文件:

您的 global.config.php 文件

<?php
return array(
    'key' => 'value'
);

您可以使用 php 简单地获取内容,包括:

function fetchConfig()
{
    include("path/to/global.config.php");
}