Zend Framework从Controller发送变量到View(最佳实践)

时间:2010-12-03 17:04:44

标签: zend-framework plugins zend-view zend-controller

我已经在Zend Framework工作了一段时间,我目前正在重构代码的某些部分。我想要消除的一件大事是我的abstract控制器类,它启动了很多变量,这些变量必须存在于我的所有控制器中,例如$success$warning和{{1 }}。这部分可以在控制器插件中完成,但是将这些变量发送到相关视图的最佳方法是什么。目前我在我的$error控制器类中使用自定义方法,我在所有控制器中调用它。

abstract

然后在我的所有控制器的所有操作中调用

protected function sendViewData(){
    $this->view->success  = $this->success;
    $this->view->warning  = $this->warning;
    $this->view->error    = $this->error;
}

我希望通过插件控制器或更适合此

的任何内容来自动执行此过程

2 个答案:

答案 0 :(得分:5)

您可以在抽象控制器中设置postDisplatch方法来初始化视图数据(请参阅“调度前和发布后挂钩”一节)。

这样,在每个操作中,您都可以初始化$this->success$this->warnning$this->error变量,并在执行操作后将其传递给视图。

答案 1 :(得分:2)

最佳pactice 是,定义一个基本控制器并让其他控制器扩展它,而不是直接调用Zend_Controller_Action方法

// Your base controller file ApplicationController.php
class ApplicationController extends Zend_Controller_Action {
       // method & variable here are available in all controllers
        public function preDispatch() {
            $this->view->success  = $this->success;
            $this->view->warning  = $this->warning;
            $this->view->error    = $this->error;
        }
}

你的其他普通控制器就像这样

// IndexController.php
class IndexController extends ApplicationController {

}

现在所有视图/布局文件中都提供了这些(成功,警告和错误)变量,在ApplicationController.php中您还可以保留共享功能其他控制器。

相关问题