New feature: afterFilter for controller

Published on and tagged with cakephp  feature

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”.

4 comments baked

  • Nate

    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.

  • JMG

    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.

  • RosSoft

    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

  • cake baker » Release Candidate 4 of CakePHP is available

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

© daniel hofstetter. Licensed under a Creative Commons License