1

我有来自 ZF2 的视图助手,由于弃用,它不再适用于 ZF3 ServiceLocatorAwareInterface

重构该类的正确方法是什么:

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

我应该使用视图助手工厂来注入服务定位器吗?如果是,应该怎么做?

4

1 回答 1

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

//...
于 2016-09-13T06:40:02.457 回答