问题
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