ZF2 - 自定义视图助手不加载 getServiceLocator

ZF2 - Custom View Helper not load with getServiceLocator

我正在尝试创建一个视图助手来 "inject" 我的 layout.phtml 的数据库值。它是一个简单字符串的结果,但是当我调用 table 网关时,它不是结果,也没有加载另一个 html.

//Conversa/src/View/Helper/Conversas.php

namespace Conversa\View\Helper;

use Conversa\Model\ConversaTable;
use Zend\View\Helper\AbstractHelper;

class Conversas extends AbstractHelper
{

    protected $sm;
    protected $mensagemTable;
    protected $conversaTable;

    public function __construct($sm)
    {
        $this->sm = $sm;
    }

    public function __invoke()
    {
        $id = $_SESSION['id_utilizador'];

        //$conversas = $this->getConversaTable()->conversasUtilizadorAll($id);
        //$conversaTable = new ConversaTable();

        $c = $this->getConversaTable()->fetchAll(); // <-When I call this, it doesn't work anymore

        $output = sprintf("I have seen 'The Jerk' %d time(s).", $this->conversaTable);
        return htmlspecialchars($output, ENT_QUOTES, 'UTF-8');
    }

    public function getConversaTable()
    {
        if (!$this->conversaTable) {
            $sm = $this->getServiceLocator();
            $this->conversaTable = $sm->get('Conversa\Model\ConversaTable');
        }
        return $this->conversaTable;
    }

    public function getMensagemTable()
    {
        if (!$this->mensagemTable) {
            $sm = $this->getServiceLocator();
            $this->mensagemTable = $sm->get('Mensagem\Model\MensagemTable');
        }
        return $this->mensagemTable;
    }
}

Module.php

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'conversas' => function ($sm) {
                $helper = new View\Helper\Conversas;
                return $helper;
            }

        )
    );
}

这里没什么好说的,因为您没有包含任何关于 发生了什么 的信息(错误消息?),但是,您的视图助手工厂看起来不正确。您的视图帮助器构造函数方法具有服务管理器所需的参数,因此您需要传递该参数:

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'conversas' => function ($sm) {
                $helper = new View\Helper\Conversas($sm);
                return $helper;
            }
        )
    );
}

此外,由于您的视图助手需要 conversaTable,最好将其传递给视图助手而不是服务管理器(因为您所依赖的服务定位器功能已在 ZF3 中删除) .