ZF2 - 自定义视图助手无法使用getServiceLocator加载

时间:2017-10-28 21:59:21

标签: php zend-framework2

我试图创建一个View Helper来注入"注入"我的layout.phtml的数据库值。它的结果是一个简单的字符串,但是当我调用一个表格网关时,它不会产生结果,也不会加载其他的html。

// Conversa / SRC /视图/助手/ 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;
            }

        )
    );
}

1 个答案:

答案 0 :(得分:1)

由于您没有包含有关发生了什么的任何信息(错误消息?),因此您的视图助手工厂看起来不正确,因此此处不多。您的视图辅助构造函数方法具有Service Manager的必需参数,因此您需要传递:

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

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