Reputation: 2113
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 CakeResponse
object 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.
Upvotes: 0
Views: 430
Reputation: 21743
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.
Upvotes: 2
Reputation: 25698
Have you tried if returning the CakeResponse object in the beforeFilter() works the same way? If not see CakeResponse::send() and Object::_stop() and do this:
$this->response->body('whatever you need here');
$this->response->send();
$this->_stop();
Upvotes: 1