如何在 Zend Framework 2 的视图中调用控制器函数?

How to call controller function in view in Zend Framework 2?

我需要在我的视图中调用控制器函数并传递参数。我试着按照这个 How to call controller function in view in Zend Framework? 但它仍然不起作用。

我的数据库中有这样的记录:

---------------
| name  | age |
---------------
| Josh  | 22  |
| Bush  | 43  |
| Rush  | 23  |
---------------

这是我的 index.phtml

foreach ($result as $rstd){
    echo "<td>".$this->escapeHtml($rstd['name'])."</td>";
    echo "<td>".$this->escapeHtml($rstd['age'])."</td>";

    //here i want to access my controller function with sending parameter by name and also display something which has i set in that function.
    echo "<td>** result from that function **</td>";
}

这是我的控制器:

public function indexAction(){
    $result = $sd->getAllRecord($this->getMysqlAdapter());
    return new ViewModel(array('result'=>$result));
}

public function getRecordByName($name){
    if($name=='Bush'){
        $result = "You'r Old";  
    }else{
        $result = "You'r Young";    
    }

    return $result;
}

我想这样显示它:

-----------------------------
| name  | age | status      |
-----------------------------
| Josh  | 22  | You'r Young |
| Bush  | 43  | You'r Old   |
| Rush  | 32  | You'r Young |
-----------------------------

你能帮帮我吗?

根据您需要实施 viewhelpers 的评论 我在这里找到了一个非常简单的解决方案。这可能对你也有用。

这里

https://samsonasik.wordpress.com/2012/07/20/zend-framework-2-create-your-custom-view-helper/

在视图中调用控制器操作被认为是不良做法。但是您可以通过使用视图助手来实现。所以你需要的是:

  • 创建您的自定义视图助手,
  • 在您的 module.config.php
  • 的可调用对象中注册视图助手
  • 然后您可以在您的视图中调用任何控制器操作

这是一个你可以使用的助手:

class Action extends \Zend\View\Helper\AbstractHelper implements   ServiceLocatorAwareInterface
{

    protected $serviceLocator;
    
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        return $this;
    }
    
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }
    public function __invoke($controllerName, $actionName, $params = array())
    {
        $controllerLoader = $this->serviceLocator->getServiceLocator()->get('ControllerLoader');
        $controllerLoader->setInvokableClass($controllerName, $controllerName);
        $controller = $controllerLoader->get($controllerName);
        return $controller->$actionName($params);
    }
}

module.config.php :

'view_helpers' => array(
'invokables' => array(
    'action' => 'module_name\View\Helper\Action',
),  
),

在您的视图文件中:

$this->action('Your\Controller', 'getRecordByNameAction');