0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();

1 Comment

Returning CakeResponse doesn't work. I've tried it. I will try your sugestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.