Tag Archives: app_controller

Access beforeFilter set variable in controller (CakePHP)

In a CakePHP application we could define an intermediate abstraction of a controller called AppController. The concept is having a Controller class defined by Cake core, writing controllers for our project and defining app_controller.php file for our common functions repeated in every controller.

In this case we usually use beforeFilter or beforeRender method in AppController in order to define some data to be transferred automatically in every controller. More about app_controller and callback functions.

When a variable is set in beforeFilter, it could be used with it's name later in CakePHP views. For example:


  2. $this->set('products', array('P1' => 'Pizza', 'P2' => 'Water'));


Any view later:


  2. <?php echo $products['P1']; ?>

But that variable could not be accessed directly in a controller function. In this case we could use viewVars array in order to access beforeFilter set variable in other controller method, which solves our problem: 


  2. function test() {
  3. $products = $this->viewVars['products'];
  4. $product_1 = $products['P1'];
  5. }



del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com