HTTP Responses

Introduction

All of your WordPress and Router controllers should return a PSR7 compliant response to be sent back to the user's browser. Lumberjack provides a number of Response types which should cover the majority of cases.

If your Controller returns a string it will be automatically converted to an HtmlResponse object with a 200 status code.

Available Response Objects

Timber Response

The most common use-case will be to render a Twig view with some associated data. Using Timber on it's own, your code would look like this:

use Timber\Timber;

...

return Timber::render('home.twig', $context);

In Lumberjack, you should take advantage of the Rareloop\Lumberjack\Http\Responses\TimberResponse object to achieve the same thing:

use Rareloop\Lumberjack\Http\Responses\TimberResponse;

...

return new TimberResponse('home.twig', $context);

Context Flattening

When passing context data to TimberResponse, any objects that implement the Rareloop\Lumberjack\Contracts\Arrayable contract will automatically be flattened to a standard PHP array. This means that it is safe to use objects such as Collection and ViewModel in your data without it causing issues with Twig.

View ModelsCollections

Redirect Response

Redirecting to a different URL can be done by returning an instance of Rareloop\Lumberjack\Http\Responses\RedirectResponse.

Adding Flash Data

If you want to redirect to a URL and also flash some data to the session, you can use the with() method.

Diactoros Responses

Lumberjack also includes the fantastic Zend Diactoros package which provides additional PSR7 compliant Response Objects.

Adding Status Code & Headers

One of the benefits of using Response Objects is that they make it easier to control the HTTP status code & headers.

All the Response Objects bundled with Lumberjack let you set both the status code and headers in their constructor.

Or if you prefer, you can use the withStatus and withHeader methods instead.

Responsable Objects

In addition to supporting PSR7 compliant responses, Controllers can also return an object that implements the Rareloop\Router\Responsable interface. These objects provide a toResponse() method that will return an instance of a PSR7 Response.

Last updated