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');

如果你真的想在你的类中进行配置(我看不出有什么理由需要这样做,而且这违反了ZF2原则),你可以包括你的配置文件:

您的global.config.php文件

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

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

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