AppController中设置的CakePHP变量在一个控制器中可见,在另一个控制器中不可见

时间:2015-12-12 17:45:25

标签: variables cakephp global-variables cakephp-2.0 cakephp-2.x

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

@Entity
@Table(name = "B")
@DiscriminatorValue("X")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)    
public class BExt extends B {
     @Column(name = "B_MY_FIELD")
     private String newField;
}

当我使用echo $ lang时,一切运行顺利;在View中以及echo $ this-> lang在任何控制器中,除了具有相应视图的控件:

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

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

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

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]

1 个答案:

答案 0 :(得分:0)

检查您是否定义了AdminController::beforeFilter()并忘记致电AppController::beforeFilter()

AdminController

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

Cookbook中的App Controller部分向您发出警告:

  

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