2

我想知道是否可以在 cakephp 的子控制器中继承/覆盖构造函数。

在我的AppController.php

我有这样的:

public function __construct( $request = null, $response = null ) {
    parent::__construct( $request, $response );

    $this->email = new CakeEmail();

    $this->_constants = array();
    $this->_constants['some_var'] = $this->Model->find( 'list', array(
        'fields' => array( 'Model.name', 'Model.id' )
    ) );
}

在我的子控制器SomeController.php中,它继承了父构造函数

public function __construct( $request = null, $response = null ) {
    parent::__construct( $request, $response );
}

当我尝试访问$this->email$this->_constants['some_var']时,它们都为空。但是,只要我将代码直接放入 SomeController.php 而不是继承,它就起作用了。

我做错了什么还是蛋糕根本无法接受?我也对函数beforeFilter()进行了同样的尝试,同样的事情发生了。但是每个控制器都有自己的beforeFilter()是有道理的。

4

1 回答 1

4

我什至不会尝试覆盖_construct' function of the appController. That's what thebeforeFilter ,beforeRender 方法。看起来您只是想从 appController 将 vars 传递给每个控制器。你可以这样做...

class AppController extends Controller {

   var $_constants = array();

   public function beforeFilter(){
      $this->_constants[] = array('this', 'that', 'the other');
   }

}

在模型的控制器中,您可以像这样访问变量...

class UsersController extends AppController {

   public function add(){
      pr($this->_constants);
   }
}

如果您尝试将变量发送到视图(稍微),那就另当别论了。只需使用 set 方法

class AppController extends Controller {

   public function beforeFilter(){
      $this->set('_constants', array('this', 'that', 'the other'));
   }

}

在任何视图中,您都可以_constants使用 . 调用变量pr($_constants);。因为它在 appController 中,所以它应该在每个视图中都可用。

于 2013-02-22T12:53:40.583 回答