Reputation: 175
I'm wondering if it is possible to inherit/override constructors in child controllers in cakephp.
In my AppController.php
I have it like this:
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' )
) );
}
and in my child controller SomeController.php, it inherits the parent constructor
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
}
and when I tried to access $this->email and $this->_constants['some_var'] they both are null. But as soon as I put the code directly in SomeController.php instead of inheriting, it worked.
Did I do something wrong or this is simply not approachable for cake? Also I tried the same with function beforeFilter(), same thing happened. But it makes sense that each controller to have its own beforeFilter().
Upvotes: 2
Views: 3931
Reputation: 4517
I wouldn't even try overriding the _construct' function of the appController. That's what the
beforeFilter,
beforeRender` methods are for. It looks like you are just trying to pass vars to each controller from the appController. You can do that like so...
class AppController extends Controller {
var $_constants = array();
public function beforeFilter(){
$this->_constants[] = array('this', 'that', 'the other');
}
}
and in your model's controller you can access the variable like so...
class UsersController extends AppController {
public function add(){
pr($this->_constants);
}
}
It's a different story if you are trying to send the variables to the view (slightly). Just use the set method
class AppController extends Controller {
public function beforeFilter(){
$this->set('_constants', array('this', 'that', 'the other'));
}
}
and in any view you can just call the _constants
variable with pr($_constants);
. Because it is in the appController it should be available on every view.
Upvotes: 4