Symfony 8.2 was released on November 28. The New in Symfony 8.2 series presented its features one at a time. This post looks at them together, in a complete application, and measures what they change.

The Symfony Showcase is a conference website: a call for papers, reviews by a committee, ticket sales, a back office, a JSON API and console commands. Its main branch runs on Symfony 8.2. Two other branches contain the same application on Symfony 8.1 and on Symfony 7.4, the long-term support version. The three versions have the same features and the same tests. When a feature is missing in an older version, it is replaced by the code you would write on that version, in a commit of its own.

The Numbers

Counted on each branch 8.2 8.1 7.4 7.4 to 8.2
PHP files in src/ 75 113 115 -35%
Lines of PHP in src/ 3,051 5,024 5,056 -40%
Lines of YAML written for the app 132 147 146 -10%
Lines of tests 1,475 1,809 1,825 -19%

The YAML lines are the ones the application adds or changes in config/, on top of what the Flex recipes install. The three versions need about the same configuration: 8.2 adds some for its new features, and moves some into attributes, like the definition of the workflow and the encrypted column. The recipes of 8.2 also install less YAML, as described below.

On 8.1, the application needs about 2,000 more lines of code and 330 more lines of tests. Most of these lines are not boilerplate. They are an OpenID Connect client, a store of encryption keys, Messenger middleware, form types and test helpers: code that 8.2 ships ready to use.

On 7.4, the application needs only 32 more lines of code than on 8.1. Symfony 8.0 has the features of 7.4 without the deprecated code, and this application uses a few features of 8.1, such as console commands declared on methods. So if your application runs on 7.4, moving to 8.2 brings almost all of the savings described below.

Login with OpenID Connect

Speakers log in with the identity provider of the conference. On 8.2, the new OpenID Connect authenticator, oidc_login, runs the authorization code flow, creates the users from their claims, refreshes their access token, and ends their session on both sides:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# config/packages/security.yaml
security:
    firewalls:
        main:
            oidc_login:
                provider_uri: '%env(OIDC_ISSUER)%'
                client_id: '%env(OIDC_CLIENT_ID)%'
                client_authentication:
                    client_secret_basic: '%env(OIDC_CLIENT_SECRET)%'
                scope: [profile, email]
                user_identifier_claim: email
                refresh_access_token: true
                enable_end_session: true
                backchannel_logout: true

On 8.1, the application does all of this itself: an authenticator that checks the state, the nonce and the PKCE code, a client for the five endpoints of the provider, a listener that refreshes the tokens, and a store of sessions for the back-channel logout. That is 4 classes and about 500 lines (OpenID Connect on 8.1).

Columns Encrypted at Rest

The phone numbers of the speakers are encrypted in the database. The new KeyManagement component, experimental in 8.2, encrypts a column with a data key that a key management service protects. An attribute marks the encrypted column:

1
2
3
#[ORM\Column(nullable: true)]
#[Encrypted(key: 'speaker.contact')]
public ?string $phone = null;

The key management service is chosen by its DSN: AWS, Azure, Google Cloud, HashiCorp Vault, KMIP, or a local key. The data keys are kept in a table:

1
2
3
4
5
6
# config/packages/key_management.yaml
key_management:
    clients:
        default: '%env(KMS_DSN)%'
    store:
        key_id: speakers

On 8.1, the application writes a Doctrine type and a store of keys, protected by a master key read from the environment: 223 more lines. Using a cloud key management service would also need its SDK (encryption on 8.1).

Messenger Flows

When a talk is accepted, the travel of the speaker is booked. The travel details are sent once the booking succeeds, and the organizers are alerted if it fails for good:

1
2
$this->bus->dispatch(ChainStamp::envelope(new BookSpeakerTravel($proposal->id), new SendTravelDetails($proposal->id))
    ->with(new DispatchOnFailureStamp(new AlertOrganizers(/* ... */))));

The messages of this Messenger flow share a correlation id, and the domain events go through an outbox, so they are only sent to RabbitMQ if the database transaction commits. On the other side, an inbox records each event in the same transaction as its handlers. When RabbitMQ delivers an event again after its handlers committed, the handlers are skipped. The outbox and the inbox are options of the transport:

1
2
3
4
5
6
7
8
9
10
11
# config/packages/messenger.yaml
messenger:
    identity_stamps: true
    transports:
        events:
            dsn: '%env(RABBITMQ_DSN)%/%%2f/events'
            outbox: 'doctrine://default?queue_name=outbox'
            inbox: true
    buses:
        messenger.bus.default:
            middleware: [logging, doctrine_dbal_transaction]

Handlers can also run in a given order, with #[AsMessageHandler(after: NotifyReviewersOfNewProposal::class)]. The logging middleware records the duration and the memory usage of each message. On 8.1, the application implements each of these itself: 8 classes, 280 lines (Messenger on 8.1 and the inbox on 8.1).

Forms from Data Classes

On 8.2, with attribute-based forms, a data class can be its own form type. The fields are declared next to the validation constraints, and their types are guessed from the PHP types:

1
2
3
4
5
6
7
8
9
10
#[AsFormType]
final class SpeakerData
{
    #[FormField]
    #[Assert\NotBlank]
    public ?string $name = null;

    #[FormField(TelType::class, ['required' => false, 'help' => 'Only given to the travel agency if your talk is accepted.'])]
    public ?string $phone = null;
}

The call for papers is a form flow with a step group, the slides and videos of a proposal are edited in one polymorphic collection, and the dates of a conference are ranges edited with BoundsType. On 8.1, the application needs 8 more form type classes, a constraint and a form theme block: 216 lines (forms on 8.1).

API Access Tokens with Scopes

The API accepts the access tokens of the identity provider. Submitting a proposal requires a scope:

1
2
#[IsGranted('OAUTH2_SCOPE(proposals:write)')]
public function submit(/* ... */): JsonResponse

A token without the scope gets the insufficient_scope error of RFC 6750. Clients find the authorization server in the metadata document of RFC 9728, which 8.2 serves from the configuration of the firewall. On 8.1: 5 classes and 199 lines (access tokens on 8.1).

Standard Webhooks

The payment provider notifies the application with signed webhooks, and a fake provider in the application sends them in development. One line makes both sides follow the Standard Webhooks specification:

1
2
3
# config/packages/webhook.yaml
webhook:
    signature_format: standard

On 8.1: 4 classes and 145 lines to sign and to check the signatures (webhooks on 8.1).

And Many Smaller Ones

The ticket sale is rate limited per user, with the X-RateLimit-* headers in the responses, and locked per conference. The key of the lock takes the conference from the arguments of the action:

1
2
3
#[RateLimit('ticket_purchase', key: new Expression('args["user"].getUserIdentifier()'), methods: 'POST', exposeHeaders: true)]
#[Lock('ticket-sale-{conference}', blocking: true, ttl: 10, methods: 'POST')]
public function buy(Conference $conference, #[CurrentUser] User $user /* ... */): Response

And more, most of them saving a class or a few dozen lines on 8.1:

  • the sudo mode: reviewers confirm their password before deciding on a proposal, when their voter requests a re-authentication;
  • the sign_url Twig filter for links that expire;
  • logout_button() and impersonation_button() in Twig, for the POST-only logout and user switching;
  • wildcards in the role hierarchy, such as ROLE_REVIEWER_*;
  • console sub-commands: bin/console conference list runs a method of the class that groups the commands about conferences;
  • #[Serialize(map: TalkResource::class, stream: true)]: the controller returns entities, the ObjectMapper maps them to API resources, and JsonStreamer streams them;
  • the default serialization groups: with enable_default_groups, the properties without #[Groups] are in every group;
  • #[Cache(target: 'CDN')] for the CDN-Cache-Control header, templated links in Link-Template headers, and errors served as application/problem+json;
  • the Cache-Status header of the HTTP cache, with one option;
  • a stateful schedule configured in YAML, without a Schedule class;
  • entities discovered by the container scan, so that doctrine.yaml needs no mappings entry;
  • one bundle per component, each configured at its own root key (messenger: instead of framework: messenger:), with a JSON schema that editors use to validate and complete the files;
  • defaults that follow the debug mode for what differs between development and production, and the framework.test option for what tests need, so that the recipes no longer write when@prod and when@test blocks for them. With these defaults, and without the lines that set a default value anyway, the YAML of this application went from 379 to 318 lines;
  • one security.route_loader that declares the routes of every firewall feature, from the logout to the OpenID Connect callbacks;
  • for tests: consumeQueuedMessages(), #[UseRecord] to replay recorded HTTP exchanges, $client->sendWebhook(), and loginUser() on an access token firewall. On 8.1, the tests need 261 more lines of helpers.

The full comparison describes each feature and links to the code that replaces it on 8.1 and on 7.4.

Performance

The versions do the same work, so they can also be compared for speed. The 8.2 and 7.4 versions were installed from fresh clones, their assets compiled with asset-map:compile as a deploy does, and served by FrankenPHP 1.12, with PHP 8.5 and OPcache, and 8 workers in worker mode. The 8.2 version runs Twig 4, with the optimizations of for loops that its first beta now includes (twigphp/Twig#5004 and the next ones); the 7.4 version runs Twig 3.30. The same twelve requests were replayed in the prod environment: four public pages, four API calls, the form of the call for papers and three pages of the back office. The last four were requested as a logged-in administrator. The HTTP cache of the kernel was turned off, so that each request does the whole work. The 8.1 version is left out: in earlier runs, it was within a few percent of 7.4.

FrankenPHP ran the application in four setups:

  • worker mode: the kernel boots once per worker, then handles one request after the other;
  • worker mode with FRANKENPHP_RESET_KERNEL, which gives each request a fresh copy of the kernel, so that no state leaks from one request to the next. It was added in Symfony 8.1, so the 7.4 version cannot run it;
  • classic mode, one PHP request per HTTP request, like PHP-FPM;
  • classic mode with opcache.preload.

Timings on a laptop vary from one run to the next, so the first table counts the CPU instructions that the twelve requests run, measured with Valgrind on the same PHP build:

Setup 7.4 8.2 Change
Worker mode 52.4 M 37.2 M -29%
Worker mode, kernel reset   70.5 M  
Classic mode, preloading 119.6 M 102.2 M -15%
Classic mode 187.4 M 167.3 M -11%

In worker mode, each of the twelve requests runs 24% to 47% fewer instructions than on 7.4, the login page gaining the most. Among other performance improvements, the container now builds a compiled event dispatcher, which gets all its listeners in one array. Twig is part of the gain: with Twig 3.30, the 8.2 version runs 38.6 M instructions in worker mode. Twig 4 alone costs 2% more, and its loop optimizations bring it 4% below Twig 3.30. In classic mode, every request boots a new kernel and declares its classes again. This costs about the same on both versions, so the gain is smaller.

The second table gives the time of the twelve requests sent one at a time, and how many requests per second 8 clients get, with PostgreSQL in Docker on the same machine:

Setup Time 7.4 Time 8.2 7.4 8.2
Worker mode 78 ms 72 ms 1,068 req/s 1,210 req/s
Worker mode, kernel reset   102 ms   852 req/s
Classic mode, preloading 144 ms 136 ms 605 req/s 673 req/s
Classic mode 210 ms 193 ms 413 req/s 443 req/s

The database takes a large part of each request, so the difference in time is smaller than in instructions. In worker mode, 8.2 answers 7% faster and serves 13% more requests per second. The worker of 8.2 also collects garbage cycles only when PHP's buffer of possible cycles is half full, while 7.4 collects them after every request. With a collection after every request, 8.2 would run 7% more instructions.

Resetting the kernel after each request costs 90% more instructions than plain worker mode. It is still faster than classic mode, even with preloading: 31% fewer instructions and 27% more requests per second.

Since Symfony 8.1, the caches that VarExporter writes, such as the metadata of Doctrine and of the serializer, are rebuilt by the deepclone_from_array() function when they are loaded. The deepclone extension implements this function in C. Without the extension, a PHP polyfill does the same work. In an earlier run, the extension saved 3% of the instructions in classic mode and 5% with preloading. In worker mode, where these caches are loaded once per worker, it made no visible difference. Install it with pie install symfony/deepclone.

Measuring also found where 8.2 did more work than needed. The ObjectMapper called the PropertyAccessor for every property, even plain public ones. The #[Serialize] listener built services that the response did not need. The kernel created the database connection while booting. #[Serialize] and the form type guesser parsed types from docblocks on every request. The attributes of controllers were created again on every request, and reading the flash messages started a session for visitors who had none. Forms resolved the options of each field and looked up the blocks of their theme more than needed, and created a new ICU formatter for each date or number field. The pages that render the import map read and encoded the same compiled files on every request. These are fixed in 8.2, along with about twenty smaller costs found while measuring. The polyfill of deepclone_from_array() also needs 27% fewer instructions now.

See It in the Profiler

In the dev environment, the application adds a "Symfony 8.2" panel to the web profiler. It lists the 8.2 features that each request uses, with links to their code, to their documentation, and to the commits of the 8.1 and 7.4 branches that replace them:

The Symfony 8.2 panel of the web profiler, listing the features used by a request of the API

The panel is a regular data collector, so it is also an example of how to add your own panel to the profiler.

Try It

You need PHP 8.5 with the intl, pdo_pgsql, amqp and sodium extensions, the Symfony CLI and Docker:

1
2
3
4
5
6
7
$ git clone https://github.com/nicolas-grekas/symfony-showcase.git
$ cd symfony-showcase
$ composer install
$ docker compose up -d --wait
$ symfony console doctrine:migrations:migrate -n
$ symfony console doctrine:fixtures:load -n
$ symfony serve -d --no-tls --port=8124

Then log in as admin@example.com with the password admin, or as alice with the password alice through the identity provider. Run git log main..origin/symfony-8.1 to list what the 8.1 version replaces, and git diff origin/symfony-8.1 main to read the difference.

Found Along the Way

Writing this application was part of the work on Symfony 8.2 during its feature freeze, when the work is about fixing and polishing what was merged. Using the new features together, the way an application does, finds problems that the tests of each feature cannot see. The ledger of the repository lists them: 64 findings, and 174 pull requests merged into Symfony, all of them in 8.2.0. Most of them target 8.2; the others fix older bugs in 6.4, 7.4 and 8.1. A few examples:

  • lint:yaml --check-schema rejected 5 of the 24 configuration files of a new project, all of them valid;
  • composer require of a component failed during its own cache:clear script;
  • when the identity provider rotated its signing keys, the oidc token handler kept the old ones in its cache, and the API answered 401 until the cache was cleared;
  • a middleware passing stamps to handlers with HandlerArgumentsStamp worked on 8.1 and failed on 8.2: porting the application to 8.1 found this break of backward compatibility before the release;
  • BoundsType replaced its object with null when both bounds were empty, so the form failed with a 500 error instead of showing a validation error.

Some features shown in this post also come from writing the application: the placeholders in the keys of #[Lock] and #[RateLimit], the logout_button() Twig function, the map and stream options of #[Serialize], #[Cache(target: 'CDN')], loginUser() on access token firewalls, and the #[Encrypted] attribute.

Symfony 8.2 is the work of many contributors. Thanks to all of them!

Published in #Community #Symfony