我正在尝试在我的实体类上使用Service Manager,但我不知道最好的方法.
在控制器上很容易,因为我们可以使用以下命令调用服务管理器:$ this-> getServiceLocator();
但是,在我的实体类中,即使我实现了ServiceLocatorAwareInterface,我也可以通过服务管理器来调用ServiceManager,因为我的实体类没有被调用:
那么最好的方法是什么:
1 - 从我的控制器2传递我的实体类中的serviceManager - 使用ServiceManager构建我的实体类3 - ...?
为了最好地理解我的问题,这是我的代码不起作用:
我的实体类:
class Demande extends ArraySerializable implements InputFilterAwareInterface {
/../
public function getUserTable() {
if (! $this->userTable) {
$sm = $this->getServiceLocator();//<== doesn't work !
$this->userTable = $sm->get ( 'Application\Model\UserTable' );
}
return $this->userTable;
}
Run Code Online (Sandbox Code Playgroud)
And*_*rew 18
我不会将ServiceManager注入您的模型中(尽管您可以).我宁愿让ServiceManager为您构建模型,并将您需要的任何内容直接注入模型中.
服务配置:
'factories' => array(
'SomethingHere' => function($sm) {
$model= new \My\Model\Something();
return $model;
},
'\My\Model\Demande' => function($sm) {
$model= new \My\Model\Demande();
/**
* Here you use the SM to inject any dependencies you need
* into your model / service what ever..
*/
$model->setSomething($sm->get('SomethingHere'));
return $model;
},
/**
* Alternatively you can provide a class implementing
* Zend\ServiceManager\FactoryInterface
* which will provide an instance for you instad of using closures
*/
'\My\Model\DemandeDefault' => '\My\Model\DemandeFactory',
Run Code Online (Sandbox Code Playgroud)
将任何依赖项放在Service Manager Config中,然后使用它将任何依赖项注入到模型,服务等中.
如果要使用工厂方法而不是闭包,请使用示例工厂类:
DemandeFactory.php
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class DemandeFactory implements FactoryInterface
{
/**
* Create a new Instance
*
* @param ServiceLocatorInterface $serviceLocator
* @return Demande
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config'); // if you need the config..
// inject dependencies via contrustor
$model = new \My\Model\Demande($serviceLocator->get('SomethingHere'));
// or using setter if you wish.
//$model->setSomething($serviceLocator->get('SomethingHere'));
return $model;
}
}
Run Code Online (Sandbox Code Playgroud)
您尝试通过Service Manager实例化的示例模型.
Demande.php
class Demande
{
protected $_something;
/**
* You can optionally inject your dependancies via your constructor
*/
public function __construct($something)
{
$this->setSomething($something);
}
/**
* Inject your dependencies via Setters
*/
public function setSomething($something)
{
$this->_something = $something;
}
// Something will be injected for you by the Service Manager
// so there's no need to inject the SM itself.
}
Run Code Online (Sandbox Code Playgroud)
在您的控制器中:
public function getDemande()
{
if (! $this->_demande) {
$sm = $this->getServiceLocator();
$this->_demande = $sm->get ('\My\Model\Demande');
}
return $this->_demande;
}
Run Code Online (Sandbox Code Playgroud)
您可以将SergiceManager/ServiceLocator注入模型,但随后您的模型将依赖于ServiceLocator.