Sending a response when beforeDispatch has returned false

Hi

I found that when returning false from a beforeDispatch event that has produced and called send() on an Http\response that no output is received by the client. Bailing out with exit() after the send does return the response to the client, but is a nasty kludge. Is there an official way to send a response when a request has been abandoned?

As an aside, I found too that returning false from a beforeDispatch event interceptor does not stop the request if a subsequent beforeDispatch interceptor returns true, It seems the last response is taken, which could be worth documenting.

Call send() manually is bad practice, what you have to do is return the response in an action, or obtain the 'response' service from the DI and call setContent() returning false from beforeDispatch.



1.9k
edited Jul '15

Hi Andres

Call send() manually is bad practice, what you have to do is return the response in an action, or obtain the 'response' service from the DI and call setContent() returning false from beforeDispatch.

I agree, and the code already does what you suggest. the event handler decides that the request cannot be processed due to security reasons and uses a responder component that accesses a DI'd $this->response and sets headers plus a Json response via setJsonContent(). Despite this the response never makes it back to the client unless we bail with exit().

Calling forward() on the dispatcher does seem to work, so it seems that it's not possible to send a response if the dispatcher has nothing to do. One view could be that if there's no request processed there cannot be a response, but on the other hand we want to send a response precisely to say that no request was processed :)



1.9k
edited Jul '15

Andres

Just so we're completely sure. Is it officially only possible to return a response if an action is processed, and observing that response content is sent if we exit() after producing a response but not otherwise, is the response effectively being discarded by phalcon and not flushed if the last beforeDispatch event handler returns false?

A response must be returned from the dispatcher. You can make $dispatcher->setReturnedValue($response) to override the response or return the response from an action.