Search code examples
cakephpbefore-filter

Proper way to end request in CakePHP 2.6 in beforeFilter


In CakePHP 2.6, sometimes i want to end the current request in the beforeFilter() callback, and maybe issue a forbidden or not found result status.

In a controller action i know i can do this by returning the CakeResponseobject but i want to this in the callback. Is there a proper CakePHP way of doing so, to ensure all callbacks are called and the app is properly processed, or can i just send the headers and call die()?

Thanks in advance.


Solution

  • By throwing exceptions you do exactly that. Nothing else necessary:

    throw new ForbiddenException();
    

    or

    throw new NotFoundException();
    

    etc.

    That is a clean way to bail early. The error/exception handler will automatically format it in the necessary output format (html, json, xml, ...) for you and will send the right headers (status code, ...).

    Never use die()/exit. Never send headers manually. It makes your code untestable.