Study guide · PHP, PSR and HTTP
The foundation under TYPO3: PHP, PSR standards and HTTP
TYPO3 stands on a foundation it did not build itself: PHP, the shared standards of the PHP world and HTTP. Here you follow the extension my_extension as it loads classes, fetches speaker data from an API, checks requests in a middleware and delivers a CSV file.
Standards of the PHP world: PSR and PER
The PHP Framework Interop Group, PHP-FIG for short, is an association of PHP projects. It publishes PSRs, PHP Standards Recommendations. A PSR defines shared interfaces or rules so that libraries fit together. It is neither part of the PHP language nor a TYPO3 standard.
A PSR passes through the stages Pre-Draft, Draft and Review. Only with the status Accepted is it final. Replaced standards are Deprecated, abandoned proposals are Abandoned.
TYPO3 uses these standards all the time:
- PSR-3 describes the logger interface.
- PSR-4 defines autoloading.
- PSR-7 describes HTTP messages, that is, request and response.
- PSR-11 describes the container for dependency injection.
- PSR-14 describes the event dispatcher.
- PSR-15 describes middlewares and request handlers. TYPO3 builds its frontend and backend stacks from them.
- PSR-17 describes factories that create HTTP messages.
- PSR-18 describes an HTTP client.
PSR-0 for autoloading and PSR-2 for coding style are deprecated, and TYPO3 uses neither.
For coding style, the current standard is the PER Coding Style. PER stands for PHP Evolving Recommendation. A PSR is frozen once accepted, while a PER grows with new PHP versions. The PER Coding Style extends and replaces PSR-12, which does not know enums, attributes or readonly yet. TYPO3 applies it through the package typo3/coding-standards.
PHP on the server
The browser never sees PHP code, only the result. A web server such as Apache or nginx accepts the request and passes it via FastCGI to PHP-FPM, a pool of PHP processes. The built-in server, started with php dash capital S, is meant for development only.
PHP extensions add extra functions. TYPO3 needs intl, for example. It provides the ICU library and formats dates, numbers and sorting to match a language and region.
- Look at the extension list on php.net. It tells you whether the extension is bundled with PHP or comes through PECL.
- Install it with the system package manager, on Debian for example the package php8.3-intl with apt.
- If needed, enable it in php.ini with extension equals intl, then restart PHP-FPM.
Composer does not install extensions. An entry ext-intl in composer.json only checks that it exists. To list loaded extensions, run php dash m, or use phpinfo() or extension_loaded() in code. Command line and web server often load different php.ini files, so check both.
Modern PHP in everyday code
Every PHP file of the extension starts like this:
<?php
declare(strict_types=1);Without this line, PHP silently converts scalar values. An int parameter then also accepts the string "5". With strict_types, the same call throws a TypeError. It applies to calls made from this file, not from other files. TYPO3 requires it everywhere.
The type ?string means: a string or null. It does not make the parameter optional, that needs a default value, and it does not reject empty strings.
The service ConferenceImporter receives its dependencies through the constructor:
public function __construct(
private readonly ConferenceRepository $repository,
private readonly LoggerInterface $logger,
) {}This is constructor property promotion. With a visibility keyword before the parameter, PHP declares and assigns the property. readonly exists since PHP 8.1. The property is set once, and every later write throws an error. Since PHP 8.2, a readonly class makes all properties readonly, handy for a value object such as Money. final only prevents inheritance.
Attributes exist since PHP 8.0, for example the attribute AsEventListener above a class. PHP checks their syntax, and frameworks read them at runtime via reflection with getAttributes(). They replace annotations in comments. In TYPO3 14, the old Extbase annotations are removed.
- Enums: A conference has a status with the cases Draft and Published.
Status::from()throws aValueErrorfor an unknown value, whileStatus::tryFrom()returns null. You cannot create an enum with new, andcases()returns a list of all cases. - match compares strictly, like the triple equals operator. The string "1" does not match the number 1. Without a matching arm and without default, match throws an
UnhandledMatchError. switch compares loosely. - The nullsafe operator, a question mark followed by an arrow, returns null when the value on its left is null. Place it directly after the call that may return null.
- Named arguments pass values by parameter name. Skipped optional parameters keep their defaults. Parameter names thus become part of the interface.
$mailer->send('a@example.org', 'Hello', priority: 1);
$city = $conference->getVenue()?->getCity();
$status = Status::tryFrom($value) ?? Status::Draft;Two traps. substr() and strlen() count bytes. An umlaut such as Ü takes two bytes in UTF-8, so for the German word Überblick strlen() returns 10, but mb_strlen() returns 9. Shorten text with mb_substr(), or you may split a character. And with DateTimeImmutable, modify() returns a new object and leaves the original unchanged. A DateTime would change itself.
Namespaces and autoloading
Without namespaces, a project could have only one class called PriceService. With a namespace such as MyVendor, MyExtension, Service, the full name is unique. At the same time, the autoloader derives the file path from the namespace. Namespaces do not control visibility.
An autoloader loads the file of a class only when the class is first used, so manual require statements disappear. PHP calls the autoloader registered with spl_autoload_register(). It does not update packages.
Under PSR-4, a namespace prefix maps to a directory. This goes into the autoload section of the extension's composer.json:
"autoload": {
"psr-4": { "MyVendor\\MyExtension\\": "Classes/" }
}Composer writes the autoloader to the file vendor/autoload.php, on composer install, composer update and composer dump-autoload. A script only includes this file, and in TYPO3 the entry point does that. Services.yaml controls dependency injection and assumes autoloading already works. Since TYPO3 14, every extension needs a composer.json, in classic mode too.
On production, run composer dump-autoload with optimize or classmap-authoritative. Composer then builds a classmap, a list of classes and files, so no file system search is needed. With classmap-authoritative, Composer looks only there, and new classes need a new dump.
HTTP: request and response
HTTP is stateless. Every request stands on its own. State across several requests comes from cookies and sessions, in TYPO3 for example the cookie fe_typo_user.
A request has a method, a URL, headers and sometimes a body:
- Browsers fetch pages with GET. GET and HEAD are safe, they should not change anything.
- POST sends data, for example from a form. POST is neither safe nor idempotent.
- PUT replaces and DELETE removes. Both are idempotent: repeating them has the same effect as running them once.
The response starts with a status code. 200 means OK. 401 Unauthorized means authentication is missing or invalid. 403 Forbidden means authenticated but without permission. 404 Not Found means the resource does not exist. 410 Gone means permanently removed. 429 Too Many Requests reports an exceeded rate limit. 500 is an internal server error, and 503 means temporarily unavailable.
If a page moves for good, use 301, or 308 to keep a POST. Search engines then adopt the new URL. After a form, 303 See Other fits. The browser loads the thank-you page with GET, and reloading does not resend the form. This pattern is called Post, Redirect, Get. The redirect method in Extbase also sends 303 by default. With 307, the browser would repeat the POST.
Headers also control caching. For personal data, send Cache-Control with no-store. It forbids any storing, in the browser and in proxies. no-cache allows storing but requires revalidation before every reuse. public even allows shared caches to store it. The older header Expires only sets an expiry time.
PSR-7: request and response as objects
PSR-7 turns HTTP messages into PHP objects. The shared base with headers and body is the MessageInterface. A RequestInterface describes an outgoing request, as sent by an HTTP client. The incoming request on the server is a ServerRequestInterface. It also knows cookies, server parameters, query parameters, the parsed body, uploaded files and attributes. Add ResponseInterface, UriInterface for the address and StreamInterface for the body.
getQueryParams()returns the URL parameters, that is, the GET parameters.getParsedBody()returns the form data, that is, the POST data.getUploadedFiles()returns uploaded files.getAttribute()returns values added by middlewares, in TYPO3 for example site or frontend.user. They never come from the visitor.
Methods like getPostParams or getSession do not exist, and TYPO3 code does not read the global POST array.
$email = $request->getParsedBody()['email'] ?? '';
$site = $request->getAttribute('site');PSR-7 messages are immutable. Every method starting with with returns a modified copy. Calling withHeader() without assigning the result changes nothing, a common mistake.
$response = $response->withHeader('X-Conference', '42');The body's read position is a different matter. The body is a stream with a pointer. getContents() reads from the current position to the end, so a second call returns nothing. If you cast the body to a string, PHP rewinds first and you get everything. Alternatively, call rewind().
PSR-15: middlewares and request handlers
PSR-15 defines two interfaces. A request handler implements the RequestHandlerInterface with the method handle(). It receives a server request and returns a response. A middleware implements the MiddlewareInterface with the method process(). It receives the request plus the next handler and also returns a response.
A middleware has three options:
- It enriches the request, for example with
withAttribute(), and passes it on with handle. - It returns its own response without calling the next handler.
- On the way back, it modifies the response of the next handler, for example by adding a header.
Output with echo contradicts the concept. PSR-15 deliberately dropped the older style with __invoke(), which received request, response and a function called next.
TYPO3 has a frontend and a backend stack. You register middlewares in Configuration/RequestMiddlewares.php.
Creating and sending messages: PSR-17 and PSR-18
PSR-7 only describes the messages, not how to create them. That is what PSR-17 is for, with six factory interfaces:
RequestFactoryInterfaceandServerRequestFactoryInterface.ResponseFactoryInterface.StreamFactoryInterface,UploadedFileFactoryInterfaceandUriFactoryInterface.
Your code then needs no concrete PSR-7 class. PSR-17 neither replaces PSR-7 nor makes anything mutable. In TYPO3, you get the factories through dependency injection. A controller of my_extension uses them to deliver a CSV file:
return $this->responseFactory->createResponse()
->withHeader('Content-Type', 'text/csv')
->withHeader('Content-Disposition', 'attachment; filename="export.csv"')
->withBody($this->streamFactory->createStream($csv));Content-Disposition with attachment makes the browser save the file. echo with exit bypasses the middleware chain. The PHP function header sets headers past the response. A JsonResponse would encode the text as JSON.
PSR-18 describes the HTTP client. The ClientInterface has the method sendRequest(). It takes a PSR-7 request and returns a PSR-7 response. It reports errors through ClientExceptionInterface, NetworkExceptionInterface and RequestExceptionInterface. A status of 400 or above is a normal response, not an error. PSR-18 does not allow request-specific Guzzle options. In TYPO3, Guzzle sits behind it, and the global settings under HTTP still apply, such as proxy and headers.
More convenient is the method request() of the TYPO3 class RequestFactory:
$response = $this->requestFactory->request($url, 'GET', ['timeout' => 5]);
$json = (string)$response->getBody();The result is a PSR-7 response, not a ready-made array. The options in the third parameter override the global values for this call. That pays off, because the global timeout is 0, meaning unlimited. Unlike the plain PSR-18 client, Guzzle throws an exception here for status 404 or 500, which you must catch.
JSON and the Symfony Finder
The speaker API answers in JSON. JSON requires double quotes around keys and strings. It knows objects, arrays, numbers, true, false and null. A comma after the last entry is not allowed, and neither are comments.
{"name": "TYPO3", "version": 14, "lts": true, "tags": ["cms", "php"]}json_encode() turns an array into JSON, and json_decode() reads it back. serialize() produces a PHP-specific format that other systems do not understand.
For invalid JSON, json_decode() normally returns null. That looks like a valid null, and only json_last_error() tells you why. It never returns false. So set JSON_THROW_ON_ERROR, and PHP throws a JsonException. The second parameter is a boolean for associative arrays, not flags.
$speakers = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
$text = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);JSON_PRETTY_PRINT adds indentation and line breaks. With JSON_UNESCAPED_UNICODE, umlauts stay readable instead of becoming Unicode escapes. You combine several flags with a vertical bar. One more trap: array_filter() keeps the keys. An array with gaps becomes an object in JSON. array_values() renumbers it, and you get a list.
Symfony is a set of reusable PHP components, a web framework built on them and a community. TYPO3 uses individual components such as Console, Dependency Injection, Routing, Mailer and Messenger, not the full framework.
The Symfony Finder searches for files and directories, including subdirectories by default. depth() limits the depth, and it ignores version control directories. Filters include name() and notName(), date() for the modification date, size() for the file size, contains() and exclude(). It returns SplFileInfo objects. Copying and deleting is the job of the Filesystem component.
$files = Finder::create()->files()->in($dir)->name('*.xlf');Key points
- PSRs are recommendations of the PHP-FIG, and final means Accepted. The PER Coding Style replaces PSR-12.
- TYPO3 14 needs PHP 8.2, usually as PHP-FPM behind Apache or nginx.
- PSR-4 maps a namespace prefix from composer.json to a directory.
- 301 and 308 are permanent, 302 and 307 temporary, and 303 is always followed by GET.
- PSR-7 objects are immutable. Assign the result of every with method.
- A middleware has process and may answer early, a request handler has handle.
- PSR-17 creates messages, PSR-18 sends them.
- json_decode with JSON_THROW_ON_ERROR makes errors visible.
Terms
- PSR
- PHP Standards Recommendation, a recommendation of the PHP-FIG.
- PER Coding Style
- The evolving coding style of the PHP-FIG, successor of PSR-12.
- Autoloader
- Loads the file of a class as soon as the class is needed.
- Classmap
- A ready-made list that maps every class to its file.
- Idempotent
- Running it several times has the same effect as running it once.
- Middleware
- A layer that processes the request and response and passes them on.
- Factory
- An object that creates other objects, in PSR-17 the HTTP messages.