在controller里使用servicemanager很简单,我们可以这样做
$sm = $this->getServiceLocator()
<?php
namespace My;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
class MyClass implements ServiceLocatorAwareInterface{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
// TODO Auto-generated method stub
$this->serviceLocator = $serviceLocator;
return $this;
}
public function getServiceLocator()
{
// TODO Auto-generated method stub
return $this->serviceLocator;
}
}
这里为什么可以用,这是因为Zend\Mvc\Service\ServiceManagerConfig
增加了一个初始化的servicemanager。
$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
if ($instance instanceof ServiceLocatorAwareInterface) {
$instance->setServiceLocator($serviceManager);
}
});