RDM LABSPORTUGUÊS

Technical article/ · 8 min read

What is PHP

Laravel Saga · Season 0 · Episode 03

PHP powers a huge slice of the web, from personal blogs to platforms with millions of users. And yet I'd bet few people around you could explain what happens between saving a .php file and seeing the result in the browser.

Today we're going to open up the engine. We'll see how code turns into execution, who manages the processes and, above all, we'll meet the characteristic that defines everything in PHP: the shared-nothing model. I promise that, after this episode, several of Laravel's decisions will start to make sense.

A language born for the web

It's worth starting with its origins, because they explain a lot. PHP appeared in 1994, created by Rasmus Lerdorf as a set of scripts for his personal page ("Personal Home Page"). Today the name has become a recursive acronym: PHP: Hypertext Preprocessor.

Notice the detail: PHP was designed for a very specific task, which is to receive a request, generate a response and finish. Other languages were born for general purposes and only later got web frameworks. PHP went the other way, with the web in its DNA from day one. Before superglobals, PHP already gave you access to request data through mechanisms like $HTTP_GET_VARS and register_globals. The $_GET, $_POST and $_COOKIE superglobals arrived in PHP 4.1.0 in December 2001.

From source code to execution

PHP is an interpreted language, but that doesn't mean it reads your code line by line as it runs. The PHP engine, called the Zend Engine, goes through several stages:

From the .php file to the resultSource code to Tokens: lexer. Tokens to AST: parser. AST to Opcodes: compiler. Opcodes to Result: Zend VM runs.Source code.php fileTokensT_FUNCTION, T_VARIABLE…ASTsyntax treeOpcodesASSIGN, ADD, ECHO…Resultthe request outputlexerparsercompilerZend VM runs
From the .php file to the result

Want to see the first stage happening? Run this code:

php<?php

print_r(array_map(
    fn ($token) => is_array($token) ? token_name($token[0]) . ' => ' . $token[1] : $token,
    token_get_all('<?php $total = $price * 2;')
));

You'll see PHP looking at your code as a sequence of pieces: T_VARIABLE => $total, then an =, and so on.

OPcache: why compile twice?

Now think about it with me. Without any optimisation, all these stages would happen on every request, for every file. A Laravel application loads hundreds of files per request. Recompiling all of that all the time would be a huge waste.

This is where OPcache comes in. It stores the compiled opcodes in shared memory. On the first request, the file is compiled; on the following ones, the ready-made opcodes are reused.

ini; production php.ini
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0   ; doesn't check whether the file changed (faster)

That last line deserves a warning. With validate_timestamps=0, PHP never notices you've changed a file. That's why, in production, the deploy process has to reload PHP-FPM (or clear OPcache) for the new code to take effect. If one day you ship a fix and "nothing changes", remember this paragraph.

What about the JIT?

Since PHP 8.0 there's been a JIT (Just-In-Time) compiler, which turns the most used opcodes into native machine code. It shines in CPU-heavy tasks, such as calculations and image processing. But typical web applications spend most of their time waiting for the database and the network, so the gain is usually small. In short: OPcache is essential; JIT is optional.

PHP's many "front doors"

The same PHP engine can run in different ways. Each of them is called a SAPI (Server API):

SAPIUse
cliCommand line: php artisan, scripts, queue workers
fpm-fcgiPHP-FPM, receiving requests from NGINX
apache2handlermod_php, PHP embedded in Apache (the old model)
frankenphpPHP embedded in FrankenPHP
bashphp -r 'echo PHP_SAPI;'   # cli

And here's a tip that has already saved me a few hours of investigation: command-line PHP and PHP-FPM can use different php.ini files. It's quite common for an extension to work in php artisan and fail in the browser, or the other way round. When that happens, check:

bashphp --ini          # which php.ini the command line uses
php -m             # extensions loaded on the command line
php -v             # version

PHP-FPM: the process manager

In the previous episode, we saw that NGINX passes requests on to PHP-FPM. Let's look inside it now.

PHP-FPM has a master process, which manages a set (pool) of worker processes. And each worker handles one request at a time.

PHP-FPM mastermanages the pool
Busy
  • worker 1 · GET /posts
  • worker 2 · POST /login
Free
  • worker 3
  • worker 4
One master, a pool of workers

You decide how many workers there are, in the pool configuration:

ini; /etc/php/8.4/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 20      ; maximum number of simultaneous workers
pm.start_servers = 5
pm.min_spare_servers = 3
pm.max_spare_servers = 8
pm.max_requests = 500     ; recycles the worker after 500 requests

The most important number here is pm.max_children. It's the limit of PHP requests happening at the same time. If all 20 workers are busy and a 21st request arrives, it waits in the queue. And if the wait is too long... remember the 504 from the previous episode? Exactly. A common way to set this number is to divide the available memory by the average consumption of a worker: with 2 GB free and 60 MB per worker, something around 33.

Shared-nothing: PHP forgets everything

We've reached the most important part of the episode. In the traditional model, with PHP-FPM, every request starts from scratch:

Each request is born and dies aloneThe request arrives to Everything new. Everything new to The code runs. The code runs to Response sent. Response sent to Everything dropped. Everything dropped to The request arrives: next request, from zero.The request arrivesat a free workerEverything newvariables, objectsThe code runsyour index.phpResponse sentback to NGINXEverything droppedmemory freednext
Each request is born and dies alone

This model is called shared-nothing. Let me show you in practice:

php<?php
// app/Counter.php

namespace App;

class Counter
{
    public static int $visits = 0;
}
php<?php
// routes/web.php

use App\Counter;
use Illuminate\Support\Facades\Route;

Route::get('/counter', function () {
    Counter::$visits++;

    return "Visits: " . Counter::$visits;
});

With PHP-FPM, you can reload this page all day long: it will always show Visits: 1. The static variable dies at the end of every request. If you want to keep something between one request and the next, you need external storage: a database, Redis, the session or a file.

Why this is a strength

  • Total isolation. A bug that messes up memory in one request doesn't affect the next.
  • Memory leaks don't pile up. Everything is freed at the end.
  • Scaling is simple. Since nothing is kept on the server, you just add more servers behind a load balancer.
  • Deploying is simple. The next request already uses the new code (after reloading OPcache).

Why this is a weakness

Now the other side of the coin. A framework like Laravel has to, on every request, load the autoloader, create the container, read the configuration and register and boot dozens of service providers. With OPcache, that takes a few milliseconds. But it's work repeated thousands of times a minute, always with exactly the same result.

You know those php artisan config:cache and php artisan route:cache commands that every deploy tutorial tells you to run? Now you know why they exist: they turn that repeated work into ready-made PHP files that OPcache serves instantly.

The other model: persistent runtimes

What if the application were loaded just once and stayed alive, serving several requests in a row? That's exactly what Swoole, RoadRunner and FrankenPHP's worker mode do. In Laravel, they're all used through Laravel Octane.

Where the boot happensRequest to Boot: PHP-FPM. Boot to Application. Request to Application: Octane. Application to Runs. Runs to Response. Scenario PHP-FPM: Boot on every request. Every request pays for the whole boot and, at the end, everything is discarded. The next one starts from zero. Path: Request, Boot, Application, Runs, Response. Scenario Octane: Boot only once. The boot happened when the worker started. The request finds the application alive, and the previous request's state too. Path: Request, Application, Runs, Response. Hint: watch out for static properties and singletons.RequestarrivesBootcontainer, providersApplicationready in memoryRunsyour routeResponsegoes outPHP-FPMOctaneRequestarrivesBootcontainer, providersApplicationready in memoryRunsyour routeResponsegoes outPHP-FPMRequestarrivesApplicationready in memoryRunsyour routeResponsegoes outOctane
Where the boot happensRequest to Boot: PHP-FPM. Boot to Application. Request to Application: Octane. Application to Runs. Runs to Response. Scenario PHP-FPM: Boot on every request. Every request pays for the whole boot and, at the end, everything is discarded. The next one starts from zero. Path: Request, Boot, Application, Runs, Response. Scenario Octane: Boot only once. The boot happened when the worker started. The request finds the application alive, and the previous request's state too. Path: Request, Application, Runs, Response. Hint: watch out for static properties and singletons.RequestarrivesBootcontainer, providersApplicationready in memoryRunsyour routeResponsegoes outPHP-FPMOctaneRequestarrivesBootcontainer, providersApplicationready in memoryRunsyour routeResponsegoes outPHP-FPMRequestarrivesApplicationready in memoryRunsyour routeResponsegoes outOctane

PHP-FPM

Boot on every request

Every request pays for the whole boot and, at the end, everything is discarded. The next one starts from zero.

Octane

Boot only once

The boot happened when the worker started. The request finds the application alive, and the previous request's state too.

watch out for static properties and singletons

Where the boot happens

The performance gain is big, because the boot gets out of the way of every request. But look at what happens to our counter: it starts showing 1, 2, 3... (per worker, since each one has its own memory). State survives between requests. Now swap "counter" for "logged-in user stored in a static property". User B may end up seeing user A's data.

That's the big thing to be careful about with persistent runtimes. And, in the saga, you'll see how Laravel's Service Container offers specific tools to deal with it.

One piece of trivia to wrap up: Node.js, Go and Java work, by default, in the persistent model. PHP is one of the few popular languages where the default is exactly the opposite.

Versions matter (a lot)

PHP has gone through a revolution, in both performance and features, over the last decade. PHP 7, from 2015, practically doubled the speed compared to 5.6. The 8 series brought richer types, attributes, enums and the JIT.

Each version gets about two years of active support and two more of security fixes. And, for this series, the number that matters is this one: Laravel 13 requires PHP 8.3 or higher. Everything we'll see from here on builds on that.

bashphp -v
# PHP 8.4.x (cli) ...

What to take into the saga

  • PHP compiles code into opcodes, and OPcache avoids recompiling on every request.
  • PHP-FPM keeps a pool of workers, and each one handles one request at a time.
  • In the traditional model, PHP is shared-nothing: every request is born and dies in isolation.
  • That makes PHP simple and safe, but forces the framework to boot on every request.
  • Persistent runtimes, like Octane, remove that repeated boot, but bring the risk of state leaking between requests.

Next episode

Now you know how PHP runs. But the PHP that Laravel 13 requires is very different from the one many people learned ten years ago. It has types, enums, attributes and a powerful Reflection API, which is the secret behind several of the framework's "magic tricks".

In the next episode, we'll get to know this modern PHP, and I'll show you how to build attribute-based routing in just a few lines. See you in episode 04.

References and further reading

Official documentation

Going deeper