Zend framework 2 accessing global config in model class

Aravind.HU picture Aravind.HU · Feb 12, 2013 · Viewed 7.3k times · Source

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;
    } 


    ......

} 

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

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

Answer

Ocramius picture Ocramius · Feb 12, 2013

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)

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.