2017-10-28 65 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中被刪除)。