我有来自ZF2的查看帮助程序因为 ServiceLocatorAwareInterface
弃用而不再适用于ZF3 .
重构该类的正确方法是什么:
<?php
namespace Site\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class SlidersList extends AbstractHelper implements ServiceLocatorAwareInterface
{
protected $_serviceLocator;
public function __invoke()
{
return $this->getView()->render(
'partials/sliders',
array('sliders' => $this->getServiceLocator()->getServiceLocator()->get('Sliders/Model/Table/SlidersTable')->fetchAll(true))
);
}
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->_serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->_serviceLocator;
}
}
我应该使用视图助手工厂注入服务定位器,如果是,应该如何进行?
1 回答
不,你应该 NOT 使用工厂注入一个
ServiceLocator
实例(从不),而应该直接注入依赖项 . 在您的情况下,您应该注入SlidersTable
服务 . 你应该这样做:1) 使您的类构造函数依赖于您的
SlidersTable
服务:2) 创建一个注入依赖项的工厂:
3) 在
module.config.php
中注册您的视图助手: