繁体   English   中英

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

[英]ZF2 - Custom View Helper not load with getServiceLocator

我正在尝试创建一个视图助手来“注入”一个数据库值到我的 layout.phtml。 这是一个简单字符串的结果,但是当我调用表网关时,它不是结果,也不会加载其他 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;
    }
}

模块.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 中删除)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM