Below you will find pages that utilize the taxonomy term “Response”
Symfony2: how to create a custom Response using an event listener
In some cases you want to return a very specific Response
in case the Request
has some properties like a certain response format.
This situation calls for an event listener, which listens to the kernel.request
event. The listener itself should be a service with some special characteristics: it has the tag “kernel.event_listener” and some extra attributes, i.e. the name of the event
to which it listens and the method
of the service that should be called when this event occurs. When you want to return a very specific Response
, you should listen to the kernel.request
event. We want the kernel to call the method onKernelRequest()
, which we will define later.
Symfony2: create a response filter and set extra response headers
Sometimes you need to make changes to the Response object, after it is returned by your controller, but before it is rendered as output to the client (e.g. the browser). You may want to set some extra response headers, or “completely mess up the content” of the response. You can accomplish this by creating an event listener that listens to the kernel.response
event. I give you a sample event listener which changes the Content-Type
header in case the requested format is “json” and the browser’s accepted response format contains “text/html”; in that case, at least in my experience, the browser doesn’t render the JSON string as plain text when the status code is 4xx or 5xx. So in these situations, the event listener changes the “Content-Type” to “text/plain”, to be sure you always get decent output in the browser.