Franz Holzinger
Franz Holzinger

Reputation: 998

How to implement self defined request attributes in TYPO3 extensions

TYPO3 12 and later use request attributes to store internal informations. How does it work to add self defined attributes in TYPO3 extensions? I could not find anything in the docs.

Request Attributes

TYPO3/typo3_src-13.2.1/typo3/sysext/core/Classes/Http/ServerRequest.php:

namespace TYPO3\CMS\Core\Http;

class ServerRequest extends Request implements ServerRequestInterface
{
    protected array $attributes = [];

Upvotes: 1

Views: 48

Answers (2)

Mogens
Mogens

Reputation: 1181

You can use a PSR-15 Middleware to achive that.

All you need is a Middleware class like:

Classes/Middleware/RequestEnrichingMiddleware.php

<?php

declare(strict_types=1);

namespace VENDOR\ExtName\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RequestEnrichingMiddleware implements MiddlewareInterface
{

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler,
    ): ResponseInterface {

        $myCustomDataArray = [
            'Foo' => 'Bar',
            'Foooo' => 'Baar',
        ];

        $request = $request->withAttribute('myCustomDataArray', $myCustomDataArray);

        return $handler->handle($request);
    }
}

And then you must register this middleware in: Configuration/RequestMiddlewares.php

<?php

return [
    'frontend' => [
        'vendor/my-middleware-identifier' => [
            'target' => \VENDOR\ExtName\Middleware\RequestEnrichingMiddleware::class,
            'after' => [
                'typo3/cms-core/response-propagation',
            ],
        ],
    ],
];

For more information see:
https://docs.typo3.org/m/typo3/reference-coreapi/main/en-us/ApiOverview/RequestLifeCycle/Middlewares.html#enriching-the-request

Upvotes: 2

Garvin Hicking
Garvin Hicking

Reputation: 526

You can use withAttribute in PSR middlewares to enrich the request. This isn't really TYPO3 specific, but a general PSR approach. See:

https://docs.typo3.org/m/typo3/reference-coreapi/main/en-us/ApiOverview/RequestLifeCycle/Middlewares.html#enriching-the-request

You can set/get any attribute (don't use a name that TYPO3 already uses though).

Upvotes: 1

Related Questions