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:

 

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

 

Any view later:

 

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

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: 

 

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

 

 

Be Sociable, Share!
  • Twitter
  • Facebook
  • email
  • StumbleUpon
  • Delicious
  • Google Reader
  • LinkedIn
  • BlinkList
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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>