ZF2 use database table model in view helper

廉价感情. 提交于 2019-12-07 23:54:30

问题


To show an database count in my layout.phtml I want to use the view helper to render ths count (set in an db field).

How do I use my database model in a view helper?

Helper:

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

Module

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

                    return $helper;
                },...

Error:

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


回答1:


create a view helper

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

and inject view_helpers via factories

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

        return $helper;
     }
    )
),


来源:https://stackoverflow.com/questions/14198052/zf2-use-database-table-model-in-view-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!