【问题标题】:ZendFramework2: Is it possible to get global.php config into a model without serviceLocator?ZendFramework2:是否可以在没有 serviceLocator 的情况下将 global.php 配置放入模型中?
【发布时间】:2016-04-07 16:18:06
【问题描述】:

在 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的原因。这应该是可能的。有了你的问题,你并没有解决实际的问题。您能否详细说明为什么您无法在侦听器中获取您的 ServiceLocator

标签: php events zend-framework2 service-locator


【解决方案1】:

您应该能够像在任何其他服务中一样通过工厂在您的侦听器中获取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 include 获取内容:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2012-10-14
    • 1970-01-01
    相关资源
    最近更新 更多