Zend framework 2 accessing global config in model class
I have a model class that does not extend the main Zend module. This model was imported from my previous Zend Framework 1. I can call its methods by translating it into a namespace. The problem is I have a global config reading aside from certain methods.
In the case of a controller, I was able to access the global config 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 the configuration in the model class. Below is an example of my model class
<?php
namespace test\Http;
class Request
{
protected $client;
public function abc( $c)
{
return $something;
}
......
}
I'm new to Zend framework 2, please suggest any method to achieve this.
In the above description, model means (MVC model class) which has some business logic in it.
source to share
Assuming you are creating your service (your code looks like a service), you will probably create an instance in the service factory (in this case, I 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 inject the config object directly into your consumer (without referencing the service locator on the consumer)
Another way is to implement Zend\ServiceManager\ServiceLocatorAwareInterface
in GaGooGl\Http\Request
. I personally discourage this , but it basically allows you to have your object Request
contain a reference to the service locator inside, so to get the service config
at runtime.
source to share