Check if an action was called from within a Controller

Posted by Felix Geisendörfer, on Jul 06, 2006 - in PHP & CakePHP » Controllers, Components & Shells

Gopher just asked me weather it was possible in CakePHP to see if an action was invoked by the dispatcher or called by $this->action();. So since I think this is one of these things that could be useful for others as well, here is my solution:

All you need to do is to check whether $this->action and the name of the function that is currently beeing executed match. This can be done like this:

php
  1. if ($this->action == __FUNCTION__)

So for example you could use it like this:

php
  1. class PostsController extends AppController
  2. {
  3.     function index()
  4.     {
  5.         $post3 = $this->view(3);
  6.     }
  7.  
  8.     function view($id)
  9.     {
  10.         $post = $this->Post->find(array('id' => $id));
  11.        
  12.         if ($this->action != __FUNCTION__)
  13.             return $post;
  14.         else
  15.             $this->render();
  16.     }
  17. }

Ok, this is a pretty useless example I have to admit, but I'm sure there are more interesting ways to utilize this ; ).

--Felix Geisendörfer aka the_undefined