Php 重构ZF2 ServiceLocatorAwareInterface以使用ZF3 in-view helper的最佳方法是什么?

Php 重构ZF2 ServiceLocatorAwareInterface以使用ZF3 in-view helper的最佳方法是什么?,php,zend-framework2,dependencies,zend-framework3,zf3,Php,Zend Framework2,Dependencies,Zend Framework3,Zf3,由于ServiceLocatorAwareInterfacedeprecation,我有来自ZF2的view helper,它不再与ZF3一起工作 重构该类的正确方法是什么: <?php namespace Site\View\Helper; use Zend\View\Helper\AbstractHelper; use Zend\ServiceManager\ServiceLocatorAwareInterface; use Zend\ServiceManager\ServiceL

由于
ServiceLocatorAwareInterface
deprecation,我有来自ZF2的view helper,它不再与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;
    }
}

否,您不应该使用工厂来注入
ServiceLocator
实例(从不),而应该直接注入依赖项。在您的情况下,您应该插入
SlidersTable
服务。你应该这样做:

1)使您的类构造函数依赖于您的
滑块表
服务:

<?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))
        );
    }
}

为什么在视图帮助器中需要服务定位器?问题在于这里,而不是如何将服务定位器提供给视图助手。我已经给出了一个答案。问题在于控制器而不是视图辅助对象,但是过程仍然是一样的。
<?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);
    }
}
//...

'view_helpers' => array(
    'factories' => array(
        'Site\View\Helper\SlidersList' =>  'Site\View\Helper\Factory\SlidersListFactory'
    )
),

//...