New feature: afterFilter for controller

beforeFilter is a nice feature of CakePHP I often use. It is a feature that exists since a long time (well, since some months *g*). In the coming Release Candidate 4 its counterpart, the afterFilter, will be added. Its usage is a little bit different from the usage of the beforeFilter we are used to. But it is still simple. You simply overwrite the afterFilter() callback function in your controller:

class MyController extends AppController
{
    function afterFilter()
    {
        echo "I am an afterFilter";
    }
}

In the same way you can define a beforeFilter. But the “old” way with the $beforeFilter variable still works:

class MyController extends AppController
{
    var $beforeFilter = array('someFunction');

    function someFunction()
    {
        echo "I am a beforeFilter";
    }
}

Personally, I prefer the new style, and so I will adapt my code. That should be easy as my functions used as before filters are already called “beforeFilter”.

3 Comments

  1. Nate
    Posted February 2, 2006 at 5:09 pm | Permalink

    The purpose of the new beforeFilter implementation is to make it easier to have a standard method, so you can implement them in AppController.

    There were also some other callbacks added: beforeRender( ), which is called immediately before a view is rendered, and startup( ), which is for components. If you are writing a component, you can use it as follows:

    function startup(&$controller) {
    //… Component initialization
    }

    This method is called immediately after beforeFilter, which allows you to set component properties there, then have the component perform “automagic” behaviors, without writing any glue code.

    The other addition to RC4 is the RequestHandler component. Just add it to your components:

    var $components = array(‘RequestHandler’);

    and all Ajax requests will automatically be rendered with the ‘ajax’ layout. Or, in your beforeFilter, you can set $this->RequestHandler->ajaxLayout to use an alternative layout.

  2. Posted February 2, 2006 at 9:51 pm | Permalink

    Wow, neat ! I already see how easy it will be to use a CacheComponent using beforeFilter and afterFilter :c)

    RC4 really appears to be promising.

  3. RosSoft
    Posted February 2, 2006 at 10:49 pm | Permalink

    Very good news the afterFilter. I requested it for making a cron-like component. After an amount of time, it will do a certain task in afterFilter, flushing the output to the user before the task


One Trackback/Pingback

  1. […] Release Candidate 4 of CakePHP has been released. Nate already described some of the new features in a comment. Some other new features are: […]

%d bloggers like this: