如何在模型中使用Zend Framework服务定位器?我有一个类,我想在中使用表网关模型。我已经按照Album的示例进行了操作,并希望在控制器之外访问表。但是,如果我将代码从控制器复制并粘贴到我需要的类中,我会得到一个错误(未定义的方法:getServiceLocator())。如何在控制器之外使用此"类"?
最后,我想访问"类AlbumTable"中的函数,而不是控制器(在这种情况下是另一个类)。谢谢
class Calendar implements ServiceLocatorAwareInterface{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
/*
* Create Calendar Sync Table
*/
public function getCalendarSyncTable()
{
if (!$this->calendarSyncTable) {
$sm = $this->getServiceLocator();
$this->calendarSyncTable = $sm->get('ProModelCalendarSyncCalendarSyncTable');
}
return $this->calendarSyncTable;
}
需要将我在控制器中的调用方式更改为
$calendar = $this->getServiceLocator()>get('ProModelGoogleCalendarCalendar');
如果您想在任何类中使用ServiceLocator,只需实现ServiceLocatorAwareInterface
。例如:
class SomeClass implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
ZendFramework2会自动将ServiceLocator的实例注入到您的类中。点击此处阅读更多关于ServiceManager的信息