Try using the newly released preload in PHP version 7.4

Tram Ho

What is preload.

Hi everyone, if you are a PHP developer like me then you will probably know that php has just released version 7.4 with some new features. Preload is a new feature added to PHP version 7.4, A feature that is expected to significantly improve the performance of your PHP app.

Preload works as follows:

  1. We have to customize a script file to specify the files we want to preload.
  2. The script we just customized above will be executed when the PHP service is started.
  3. All preloaded files will be stored on RAM and used to process incoming requests.
  4. When you change a preloaded file, the change will not be applied until you restart the PHP service.

Preload example

Install php7.4-fpm and nginx: You refer here Config php7.4-fpm: Open the file /etc/php/7.4/fpm/php.ini and edit the following config:

Config nginx: Edit the content of the file / etc / nginx / sites-enabled / default to:

Create the directory containing the code you want to preload: In my example, I created a directory named php74 in / etc / www /. The php74 directory has the following structure:

The contents of the files are as follows:

Here if you reload nginx and access it from the browser, you will get the error "B does not know the class" Edit the content of the preload.php file to:

Next we reload the service php7.4-fpm and nginx. Accessing http: // localhost will get the result:

After restarting php7.4-fpm, as specified in the preload.php file, the php74 directories will be loaded into RAM and will be executed on the next request. But the file has been preloaded, then when you edit again, the new changes will not be applied until you restart the service php7.4-fpm. Now let's try to change the content of the A.php file to

After reloading the browser, the browser is still 'Hello PHP 7.4' => our changes in the A.php file have not been applied yet. If we now restart php7.4-fpm, our changes will be applied.


As mentioned at the beginning, the use of preload will greatly improve the performance of the app. You can refer to the results of benchmarks when using Ben Morel's preload here. According to Ben Morel's share, you can decide to just pre-load "hot class" – classes commonly used in your codebase. Ben Morel's benchmark shows that only about 100 hot classes are downloaded, actually providing better performance than preloading everything. Preloading all classes only increases the performance by 13%, while pre-loading of hot classes increases the efficiency by 17%.

So through the article I introduced and the preload example in PHP version 7.4, I hope my article will bring useful information to you.

Share the news now

Source : Viblo