【发布时间】:2015-01-02 05:41:54
【问题描述】:
是否可以在控制器内包含特定操作的视图助手。
事情是这样的,我正在显示一个带有事务记录的表,但在将其显示到 html 表之前,我必须从其他服务返回的记录中获取一些视图逻辑。这个逻辑不适合放在Service端和视图中。所以我认为这就是 ViewHelper 的用武之地。
从网络上的教程中,他们将 viewhelper 放在 module.config.php 中,并将其包含在 Module.php 的引导部分中。现在,如果 viewhelper 在另一个控制器或诸如“url”之类的操作中全局使用,则可以这样做。 Buy my helper 仅用于一个控制器内的这一操作。
这是部分操作代码以及我目前如何将 viewhelper 集成到 Controller 中
<?php
function listAction() {
$viewModel = new \Zend\View\Model\ViewModel();
$service = $this->getServiceLocator();
$transactionService = $service->get('TransactionService');
$records = $transactionService->getTransaction();
$helper = new \Transaction\View\Helper\TransactionViewHelper();
$helper->setServiceLocator($service);
$records = $helper->render($records);
$viewModel->setVariable('records', $records);
return $viewModel();
}
?>
它并不优雅,它可以工作,但也许有更好的方法
viewhelper 的结构是这样的,我需要 servicelocator,因为我不知道如何在我的 viewhelper 中获取“url”viewhelper,我需要阅读一些配置。也永远不会在 list.phtml 中调用 helper
<?php
class TransactionViewHelper extends \Zend\View\Helper\AbstractHelper implements \Zend\ServiceManager\ServiceLocatorAwareInterface {
public function setServiceLocator(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function __invoke()
{
return $this;
}
public function render($records)
{
//Some logic here
return $result;
}
}
?>
【问题讨论】:
标签: php zend-framework2