由于ServiceLocatorAwareInterface
弃用,我有来自ZF2的视图帮助程序不再适用于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;
}
}
我应该使用view helper factory注入服务定位器吗?如果是,应该如何进行?
答案 0 :(得分:3)
不,你应该不使用工厂注入ServiceLocator
实例(从不),而应该直接注入依赖项。在您的情况下,您应该注入SlidersTable
服务。你应该这样做:
1)让您的类构造函数依赖于您的SlidersTable
服务:
<?php
namespace Site\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Sliders\Model\Table\SlidersTable;
class SlidersList extends AbstractHelper
{
protected $slidersTable;
public function __construct(SlidersTable $slidersTable)
{
return $this->slidersTable = $slidersTable;
}
public function __invoke()
{
return $this->getView()->render(
'partials/sliders',
array('sliders' => $this->slidersTable->fetchAll(true))
);
}
}
2)创建一个注入依赖项的工厂:
<?php
namespace Site\View\Helper\Factory;
use Site\View\Helper\SlidersList;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class SlidersListFactory implements FactoryInterface
{
/**
* @param ContainerInterface $container
* @param string $requestedName
* @param array|null $options
* @return mixed
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$serviceManager = container
$slidersTable= $container->get('Sliders/Model/Table/SlidersTable');
return new SlidersList($slidersTable);
}
}
3)在module.config.php
:
//...
'view_helpers' => array(
'factories' => array(
'Site\View\Helper\SlidersList' => 'Site\View\Helper\Factory\SlidersListFactory'
)
),
//...