【问题标题】:How to call controller function in view in Zend Framework?如何在 Zend Framework 的视图中调用控制器函数?
【发布时间】:2012-10-19 09:37:29
【问题描述】:

在 Zend Framework 中,我有一个控制器

class TestController extends Zend_Controller_Action
{

    public function indexAction()
    {

    }

    public function getResultByID( $id )
    {
        return $id;
    }

}

如何在 index.phtml 中调用 getResultByID 函数?

【问题讨论】:

  • 真的需要调用视图中的getResultByID()吗?为什么不在控制器中调用该方法并将结果传递给视图(这将是更标准的方法)?

标签: php function zend-framework controller


【解决方案1】:

第一:

public function indexAction()
{
  $this->view->controller = $this
}

在您的视图脚本中:

<html><title><?php echo $this->controller->getResultByID($this->id); ?></title></html>

【讨论】:

  • 这是我想说的最好的答案。为什么人们不接受!
  • zend 3 问题:我们如何获取 cms 页面标题及其链接以在整个网站的页眉/页脚部分显示它们。页面标题和链接存储在数据库中。请分享任何建议。谢谢。
【解决方案2】:
【解决方案3】:

如果indexAction 被执行,你可以从那里调用它:

public function indexAction()
{
    $this->getResultByID( (int) $_REQUEST['id'] );
}

【讨论】:

  • 所以不能直接在视图中调用函数?
【解决方案4】:
  public function getResultByID( $id )
  {
               return $id;
  }

你可以用上面的代码代替

  public function getResultByID( $id )
    {
         this->view->id=$id;
         this->render('index.phtml');
     }

那么你可以使用 index.phtl 中 id 的值作为this-&gt;id

【讨论】:

    【解决方案5】:

    试试这个代码我认为这是最好的选择

    public function indexAction()
        {
           $this->view->assign('id' => $this->getResultByID($this->_request->getParam('id', null)))
        }
    
        public function getResultByID( $id = null )
        {
            return $id;
        }
    

    在视图中:echo $this-&gt;id

    【讨论】:

      【解决方案6】:

      在您的 indexAction 方法中,以数组的形式返回 getResultByID 方法。

      控制器:

      public function indexAction()
      {
          return array(
             'getResult' => $this->getResultByID($id),
          );
      }
      
      public function getResultByID($id)
      {
          return $id;
      }
      

      问题是你从哪里得到 $id。无论如何,在这样的变量中调用 getResult 字符串。

      查看:

      echo $getResult;
      

      就是这样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-21
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 2011-04-23
        相关资源
        最近更新 更多