我不会将 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',
将您的任何依赖项放在服务管理器配置中,然后使用它为您将任何依赖项注入您的模型、服务等。
如果您想使用工厂方法而不是闭包,则可以使用示例工厂类:
需求工厂.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;
}
}
您尝试通过服务管理器实例化的示例模型。
需求.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.
}
在您的控制器中:
public function getDemande()
{
if (! $this->_demande) {
$sm = $this->getServiceLocator();
$this->_demande = $sm->get ('\My\Model\Demande');
}
return $this->_demande;
}
您可以将 SergiceManager/ServiceLocator 注入您的模型,但您的模型将依赖于 ServiceLocator。