CakePhp callbacks

1 Jan

Before going to discuss how to create components, models and other stuff in cakePhp I would like to tell you about some important functions called callback, that can be defined in your controller classes and these can play a very vital role in some situations.

  1. beforeFilter : This function, if defined in your controller class, is called before any action is called.

If you have worked in Zend framework and have heard about or used pre and post dispatch hooks, you may have better idea of this. Zend provides preDispatch() function which is called before any action is called. So this beforeFilter is similar to Zend framework preDispatch() method.

This function can be very helpful for the functionality like checking and activating session before action is called or more importantly to check user(s) role(s) before any controller action is called. The most simple example would be


class AuthController extends AppController


function beforeFilter()


// put code which you want to be executed before each action


function index()


// action logic here



so whenever you call

localhost/cake/auth/index, function beforeFilter() will be called and the code in it will be executed before the code in the index() action.


This function as its name indicate, is called after the action logic but before rendering the view template code. This function is rarely used.

3. afterFilter() : this function is like postDispatch() hook of the Zend framework. It is called after everything, i.e action and view template code, is executed.


One Response to “CakePhp callbacks”

  1. prabha January 11, 2010 at 5:21 pm #

    Please explain Model and callback implementation with an example.

    Thanks in advance..

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: