重构ZF2 ServiceLocatorAwareInterface以在视图助手中使用ZF3的最佳方法是什么?

时间:2016-09-12 14:25:15

标签: php zend-framework2 dependencies zend-framework3 zf3

由于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注入服务定位器吗?如果是,应该如何进行?

1 个答案:

答案 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'
    )
),

//...