Laravel: Preload your app without writing anything

Because everyone wants to preload in PHP 7.4 without the headaches

Italo Baeza Cabrera
2 min readDec 27, 2019
Photo by Goh Rhy Yan on Unsplash

Some weeks ago I created a package to make a ready-to-use Preload generator with a list of files. This list is not created randomly; it follows a very basic premise to create a useful list: load the most requested files first, until a given memory limit.

While this works for anything, I decided to publish how I use it with Laravel, which is pretty much a hands-off installation.

In that moment, Laraload was born.

Hands-off preloading scripts

What Laraload does is very simple: each given number of Requests done to the application it recreates a Preload script ready to use.

How to do this in a “transparent” way? Well, I use a Terminable Middleware. I’m not too keen on how these middlewares are handled by Laravel — it re-instances every middleware after the application sends the response — but anyway it offers a way to run code without hindering any preceding logic.

Basically, the package registers a global terminable middleware that checks if you’re not testing, and if the response is not an error (any HTTP 2xx/3xx code). After that, it will instance a class or callable and check any kind of logic. If the logic returns true, it will create the script, otherwise it won’t do nothing.

The packages comes with a very basic but useful Condition out of the box: every 500 requests, create a Preload script. This would allow your application to have good Opcache statistics and have an up-to-date Preload script that reflects your application demand.

Everything is configurable, like the condition, the output path, the memory usage, and the files to exclude or include. While it’s install-and-forget, you can still configure it to have more control, specially when using your own conditions to trigger the Preload script.

And yes, it uses Events to let you get an Slack notification or an Email to know how the generation went.

Give it a go. As always, I’m open to issues and pull requests.

--

--

Italo Baeza Cabrera
Italo Baeza Cabrera

Written by Italo Baeza Cabrera

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor. https://italobc.com

No responses yet