ZF2在视图助手中使用数据库表模型 [英] ZF2 use database table model in view helper
问题描述
要在我的layout.phtml中显示数据库计数,我想使用视图助手来显示该计数(在db字段中设置).
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?
助手:
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行的
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
推荐答案
创建视图助手
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
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;
}
)
),
这篇关于ZF2在视图助手中使用数据库表模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!