Responses overview

Last updated on
13 October 2016

What?

HTTP is all about requests and responses. Drupal 8 represents the responses it sends as Response objects. Drupal 8's responses are Symfony Response objects. Their documentation also applies to Drupal 8. First read that :)

Drupal 8 core's additions

Symfony's Response objects are fully supported, but are insufficient to fully support the rich Drupal ecosystem: we need more structured metadata than the very simple Symfony Response objects can provide.

Unfortunately, Symfony Response objects do not have an interface: every specialized Response "type" needs to extend from Symfony's Response base class.

Drupal 8's additional response interfaces

Drupal 8 core defines two response interfaces that any response can implement to indicate it supports these particular Drupal capabilities.

CacheableResponseInterface
An interface for responses that can expose cacheability metadata. (Cache contexts, tags and max-age.)
Note: can easily be implemented by using the corresponding CacheableResponseTrait.
See CacheableResponseInterface for more about this!
AttachmentsInterface
An interface for responses that can expose #attached metadata. (Asset libraries, <head> elements, placeholders …)
Note: can easily be implemented by using the corresponding AttachmentsTrait.

Drupal 8's additional response classes

Finally, to make discovery easier, here are the most important specialized Response subclasses that are available to developers.

CacheableResponse
A response that contains and can expose cacheability metadata. Supports Drupal's caching concepts: cache tags for invalidation and cache contexts for variations.
This is simply class CacheableResponse extends Response implements CacheableResponseInterface {}.
HtmlResponse
This is what a controller returning a render array will result in after going through the Render API and its render pipeline.
This is simply class HtmlResponse extends Response implements CacheableResponseInterface, AttachmentsInterface {}.
CacheableJsonResponse
A JsonResponse that contains and can expose cacheability metadata.
This is simply class CacheableJsonResponse extends JsonResponse implements CacheableResponseInterface {} — i.e. it extends Symfony's JsonResponse.
CacheableRedirectResponse
A RedirectResponse that contains and can expose cacheability metadata.
This is simply class CacheableRedirectResponse extends RedirectResponse implements CacheableResponseInterface {} — i.e. it extends Symfony's RedirectResponse.
LocalRedirectResponse
A redirect response which cannot redirect to an external URL. (Extends CacheableRedirectResponse.)
TrustedRedirectResponse
A redirect response which should only redirect to a trusted (potentially external) URL. (Also extends CacheableRedirectResponse.)

Response caching

See CacheableResponseInterface.