Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always call a function in cakePhp

Tags:

cakephp

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.

like image 593
NH3 Avatar asked Dec 11 '22 19:12

NH3


1 Answers

Put the code in your AppController.phps 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().

like image 67
Dave Avatar answered Jan 03 '23 13:01

Dave