问题
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 .
回答1:
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.
回答2:
simplest way to do this
$config = new \Zend\Config\Config( include APPLICATION_PATH.'/config/autoload/global.php' );
回答3:
Check this. It has two solutions. One is implementing a Service locator aware interface. Another is to inject the service manager into your model. For both, you need to instantiate your model object through the service manager.
来源:https://stackoverflow.com/questions/14838181/zend-framework-2-accessing-global-config-in-model-class