2访问模型类中的全局配置

2访问模型类中的全局配置

本文介绍了Zend Framework 2访问模型类中的全局配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型类,它没有扩展任何核心Zend模块.该模型是从我以前的Zend framework 1应用程序导入的.我可以通过将其转换为namespace来调用其方法.我所遇到的问题是在读取定义的方法旁边的全局配置时.

I have a model class which does not extend any core Zend module . This model was imported from my previous Zend framework 1 application . I am able to call its methods by converting it to namespace . The problem what I have is in reading global configuration in side the methods defined .

在控制器的情况下,我可以使用以下代码访问全局配置

In case of controller I was able to access global configuration using below code

 $config = $this->getServiceLocator()->get('config');

// This gives a union of global configuration along with module configuration .

但是我们应该怎么做才能访问模型类中的配置.下面是我的模型类的方式

But what should we do to access configuration in side a model class .Below is how my model class is

<?php
namespace test\Http;

class Request
{

    protected $client;

    public function abc( $c)
    {
        return $something;
    }


    ......

}

我是Zend Framework 2的新手,请提出实现此目的的任何方法.

I am new to Zend framework 2 please kindly suggest any method to achieve this .

在上面的描述中,模型工具(MVC模型类)中包含一些业务逻辑.

In the above description model means ( MVC model class ) which has some business logic in it .

推荐答案

假设您构建了服务(您的代码看起来像是服务),则可能会在服务工厂中实例化它(在这种情况下,我将其放入了模块配置):

Assuming that you build your service (your code looks like a service) you will probably instantiate it in a service factory (in this case I've put it in the module config):

class MyModule
{
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'my_request_object' => function (
                    \Zend\ServiceManager\ServiceLocatorInterface $sl
                ) {
                    $config = $sl->get('config');

                    return new \GaGooGl\Http\Request($config);
                },
            ),
        );
    }
}

这样,您将配置对象直接注入到它的使用者中(而无需在使用者中引用服务定位器)

This way, you are injecting the config object directly in its consumer (without having a reference to the service locator in the consumer)

另一种方法是在GaGooGl\Http\Request中实现Zend\ServiceManager\ServiceLocatorAwareInterface.我个人不鼓励,但基本上,这使您可以让Request对象在内部保留对服务定位器的引用,因此可以在运行时检索config服务.

Another way is to implement Zend\ServiceManager\ServiceLocatorAwareInterface in your GaGooGl\Http\Request. I personally discourage it, but this basically allows you to have your Request object keep a reference to the service locator internally, therefore making it possible to retrieve the config service at runtime.

这篇关于Zend Framework 2访问模型类中的全局配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 22:01