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


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

我需要在视图中调用一个控制器函数并传递参数。我试着遵循以下内容:如何在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 |
-----------------------------

你能帮我吗?

在考虑到的不良做法中调用视图中的控制器操作。但是您可以通过使用视图辅助对象来实现这一点。所以你需要的是:

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

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

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');

根据注释,您需要实现viewhelper我在这里找到了一个非常简单的解决方案。这可能对你也有用。

ZF2-如何从视图中调用自定义类php的函数?

这里是

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