1

在 cakephp 2.0 中,我试图在 AppController 中设置一个变量,以便可以通过以下方式在任何子类和视图中访问它:

function beforeFilter() {       
    $this->set('lang', self::getCurrentLanguage()); // set to access it also from Views
    $this->set('conf', self::getConfig());          // set to access it also from Views     
    $this->lang = self::getCurrentLanguage();   // set to access it also from Controllers
    $this->conf = self::getConfig();            // set to access it also from Controllers
    $this->set('user', $this->Session->read('User'));
    $this->user = $this->Session->read('User');     
}

当我使用 echo $lang; 时,一切都运行顺利;在 View 和 echo $this->lang 中的任何控制器中,除了一个具有各自视图的控制器:

echo $conf;
echo $lang;
---
Notice (8): Undefined variable: conf [APP\views\admin\products.ctp, line 7]
Notice (8): Undefined variable: lang [APP\views\admin\products.ctp, line 8]

由于类 AdminController 扩展了 AppController,我期望与 AppController 的任何其他子类具有相同的行为。已经花了半天时间找出问题所在。调查的起点在哪里?我应该先检查什么?

AdminController 有什么问题,因为它没有“看到”这些变量,但其他类没有这个问题?这是适用于这个特定类的唯一解决方法:

$this->set('conf', parent::getConfig());
4

1 回答 1

0

检查您是否已定义AdminController::beforeFilter()并忘记调用AppController::beforeFilter().

AdminController

public function beforeFilter() {
    parent::beforeFilter();
}

Cookbook 中的App Controller部分会警告您:

还要记住在子控制器回调中调用 AppController 的回调以获得最佳结果:

于 2015-12-12T18:06:57.933 回答