Developing software in the Real World

Implementing CORS in Zend Expressive

On a recent project, I needed to implement CORS support for my Expressive API. The easiest way to do this is to use Mike Tuupola's PSR-7 CORS Middleware. As this is a standard Slim-Style PSR-7 middleware implementation, we need to wrap it for Expressive, so we make a factory: App/Factory/CorsMiddlewareFactory.php:

We then register this in our App\ConfigProvider::getDependencies() by adding to the factories key so that it looks something like this:

If you don't… continue reading.

Customising Whoops in Expressive

I find the Whoops error handler page in Expressive quite hard to read and particularly dislike that the error message displayed in the top left is hidden if it's more than a few words long. To fix this, I discovered that you can provide a custom CSS file to the PrettyPrintHandler and then override to your heart's content! One way to do this is to add a delegator factory to add the additional functionality, so… continue reading.

OuputBuffer Middleware for Expressive

When developing an Expressive application, if you use var_dump(), echo, print_r(), etc when you get this error:

This occurs after your data has been displayed and makes perfect sense as Expressive is unable to send headers as you've already started sending the body. To solve this, you need some middleware. It looks like this:

This middleware wraps all subsequent middleware in an output buffer and then either appends or prepends the contents to… continue reading.

Displaying errors in Expressive with Twig

If you're not using the Whoops error handler with Expressive and are using the Twig renderer, then you are given no information about the problem that occurred, even in debug mode. To fix this, I changed error.html.twig to this:

The new part is the within the {% if error %} block. In debug mode, error is set to the exception that was thown and is blank otherwise, so you won't leak sensitive information (as… continue reading.