ZF2在视图助手中使用数据库表模型

时间:2013-01-07 14:37:32

标签: database model zend-framework2 view-helpers

要在layout.phtml中显示数据库计数,我想使用视图助手来渲染计数(在数据库字段中设置)。

如何在视图助手中使用我的数据库模型?

助手:

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;
                },...

错误:

  

捕获致命错误:传递给Application \ Model \ MyeCountTable :: __ construct()的参数1必须是Zend \ Db \ TableGateway \ TableGateway的实例,没有给出,在/ usr / local / zend / share / ZendFramework2 /中调用第175行的library / Zend / ServiceManager / AbstractPluginManager.php,在

中定义

1 个答案:

答案 0 :(得分: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

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

        return $helper;
     }
    )
),
相关问题