I need the request object (PSR-7, ServerRequestInterface) in my DI container. How can I add and use it? The request object will be handled through the middlewares and delivered as argument to the closure or controller action of the matchting route. But I need it for a dependency of the URI extension of Plates.
You can do this by implementing a custom Middlware that adds the Plates URI extension to the engine.
Here is an example:
<?php
namespace App\Middleware;
use League\Plates\Engine;
use League\Plates\Extension\URI;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class PlatesMiddleware implements MiddlewareInterface
{
private Engine $engine;
public function __construct(Engine $engine)
{
$this->engine = $engine;
}
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
// Load URI extension using a PSR-7 request object
$this->engine->loadExtension(new URI($request->getUri()->__toString()));
return $handler->handle($request);
}
}
Add the PlatesMiddleware before the RoutingMiddleware.
use App\Middleware\PlatesMiddleware;
$app->add(PlatesMiddleware::class);
$app->addRoutingMiddleware();
This example assumes that you have installed a DI container, e.g. PHP-DI.
The Request and Response objects are context-specific and therefore have a different life cycle. These two objects should (must) therefore never be in the DI container.