2017-10-28 110 views
1

我想创建一个视图帮助“注入”到我的layout.phtml数据库值。它的结果是一个简单的字符串,但是当我调用一个表格网关时,它不是结果,也不会加载另一个html。ZF2 - 自定义视图帮助不加载getServiceLocator

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

     ) 
    ); 
} 

回答

1

不是很多,因为你没有包含有关任何信息在这里继续什么发生(错误消息?),但是,您的视图助手工厂看起来不正确。您的视图助手的构造方法对服务管理所需的参数,所以你需要传递的是:

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

此外,由于您的视图助手要求conversaTable,它可能是更好的传递给视图助手,而不是服务管理器(作为您所依赖的服务定位器功能已在ZF3中被删除)。