Always call a function in cakePhp

cakephp

Solution

Put the code in your `AppController.php`s beforeFilter()

If you use the `beforeFilter` in other controllers make sure to call `parent` before the other code.

public function beforeFilter() {
    parent::beforeFilter();
    // your other code
}

In each controller, the `beforeFilter()` is called, which then triggers the AppController (parent) `beforeFilter()`.

Problem

I would like to know how I can use a function in cakePHP that will always be call when I load a page? More precisions with this example: I have my main page: index.ctp I have another page: profil.ctp What I want is, when I try to access profil.ctp, if I'm not logged, it will automatically redirect me to the index.ctp page. What I already done: UsersController: ``` function index() { if (!empty($this->data)) $this->Session->write(array('User' => array('connected' => true))); } ``` ProfilsController: ``` function index() { if (!$this->Session->read('connected')) $this->redirect(array('controller' => 'users', 'action' => 'index')); } ``` The problem is that I don't want to add this code to each pages, and each functions of all my controllers. Any ideas ? Regards.

Original source