2013-01-07 31 views
2

在我的layout.phtml中顯示數據庫計數我想使用視圖幫助器來呈現計數(在db字段中設置)。ZF2在視圖幫助器中使用數據庫表模型

如何在視圖助手中使用我的數據庫模型?

助手:

namespace Application\View\Helper; 

use Zend\View\Helper\AbstractHelper; 

class CountHelper extends AbstractHelper 
{ 
    protected $count; 

    public function __invoke() 
    { 
     return $this->count(); 
    } 

    public function setTableCount($sm, $myCountTable) 
    { 
     $this->count = $sm->get($myCountTable)->getCount(); 
     return $this->count;   
    } 
} 

模塊

public function getViewHelperConfig() 
    { 
     return array(
      'factories' => array(
       'CountHelper' => function($sm) { 
        $helper = new \Application\View\Helper\CountHelper(); 
        $helper->setTableCount($sm, 'Application\Model\MyCountTable'); 

        return $helper; 
       },... 

錯誤:

Catchable fatal error: Argument 1 passed to Application\Model\MyeCountTable::__construct() must be an instance of Zend\Db\TableGateway\TableGateway, none given, called in /usr/local/zend/share/ZendFramework2/library/Zend/ServiceManager/AbstractPluginManager.php on line 175 and defined in

+0

view_helpers有在看這個答案來自@ Jurian作了-sluiman - > http://stackoverflow.com/questions/14175009/zf2-service-locator/14180345#14180345 – Crisp

+0

感謝我更新了上面的代碼 – directory

+0

在你的'getViewHelperConfig()'把'$ helper-> setTableCount()'行更改爲以下內容,'$ helper-> setTableCount($ sm-> getServiceLocator(),'Application \ Model \ MyCountTable');' – Crisp

回答

1

創建視圖助手

namespace My\View\Helper; 
use Zend\View\Helper\AbstractHelper; 

class CounterHelper extends AbstractHelper 
{ 
    protected $count; 

    public function __invoke() 
    { 
     return $this->count; 
    } 

    public function setTableCount($sm, $mytablemodel) 
    { 
     $this->count = $sm->get($mytablemodel)->getCountedData(); 
     return $this->count; 
    } 
} 

個,並通過注入工廠

'view_helpers' => array(
    'factories' => array(
    'counter_helper' => function($sm) { 
     $helper = new \My\View\Helper ; 
      $helper->setTableCount($sm, 'mytablemodelthatalreadyregisteredinSM'); 

     return $helper; 
    } 
    ) 
), 
+0

感謝您的回答!我理解過程,但是我得到關於構造函數的錯誤。我更新了我的代碼+錯誤輸出。希望你能幫助:)謝謝! – directory

+0

這看起來像不工作。 – Chali

+0

$ helper-> setTableCount($ sm,'mytablemodelthatalreadyregisteredinSM');不要觸發器 – Chali

相關問題