10. 3. 2020

In April 2019 we upgraded Glami's big codebase to follow PSR-4.

It was a great success! In this part, we will go through what PSR-4 is and it's benefits.

What is PSR-4?

PSR-4 is standard for autoloading classes in the PHP world, supported for example by composer or by PHPStorm since 2014.

In short, you must register namespace prefix to a directory and every class fully qualified name must follow certain standards. As well only having a single class per file is allowed and it must match (without the .php extension).

Example is worth 1000 words here:

Fully Qualified Class Name Namespace Prefix Base Directory Resulting File Path Acme\Log\Writer\File_Writer Acme\Log\Writer ./acme-log-writer/lib/ ./acme-log-writer/lib/File_Writer.php Symfony\Core\Request Symfony\Core ./vendor/Symfony/Core/ ./vendor/Symfony/Core/Request.php Rector\Website\Demo\Controller\DemoController Rector\Website ./src ./src/Controller/DemoController.php

Following PSR-4 + using composer for autoloading allows you to rapidly create classes and use them instantly, without bothering about loading them manually.

It is really simple, just check autoloading definition in composer.json of this website:

{ "autoload": { "psr-4": { "Rector\\Website\\": "src", "Rector\\Website\\Blog\\": "packages/Blog/src" } } }

Why should you want it?

Without PSR-4 it's a mess!

Most of the popular tools (like Rector, PHPStan or Psalm) expects you to have solved the question of autoloading already or they most likely will not be able to process your code.

In Glami, for autoloading classes, they were originally using a combination of Nette RobotLoader (a great tool for autoloading, if you do not mind about PSR-4 at all) and on some places, for performance reasons, including the files manually.

Having 5 classes in the same file was a common thing, making the need for finding a specific class for the developer much more difficult.

We found "dead" PHPUnit test cases - not running, because of not following the standard! For example class MySomeClassTest in file MySomeClass.php and because of the default *Test.php file filter in PHPUnit, these tests were simply ignored.

Glami is very focused on performance. Because there are no publicly documented performance outcomes of switching to PSR-4 autoloading, we did not know what to expect.

And we were quite surprised the after first tests! Glami was globally faster by 2-4ms!

In one of the most business-critical parts, response time lowered from 8ms to 6ms. That is an incredible 25% performance gain for this specific scenario just by following a PSR-4 standard!

In the next parts, we will look more into the migrated codebase and migration process itself.

Don't you have a PSR-4 compatible application yet? Let us help you achieve this great success too!