Hi all. I am start learn Slim 4. I want to save old data from my form to session (for render in twig template). In Slim 3 I can get DI container into middleware like this https://prnt.sc/qf7n7x
But in Slim 4 I can’t do it. I don’t have DI container in $this(middleware)
How I can get DI container in my middleware?
class OldInputMiddleware
{
/**
* Example middleware invokable class
*
* @param ServerRequest $request PSR-7 request
* @param RequestHandler $handler PSR-15 request handler
*
* @return Response
*/
public function __invoke(Request $request, RequestHandler $handler): Response
{
$response = $handler->handle($request);
/*
* How get DI this?
*/
return $response;
}
}
Instead of fetching the objects from the container, you can (should) let the DI container inject the declared dependencies into your objects via (constructor) dependency injection. The container itself should not be injected.
Example:
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class SessionMiddleware implements MiddlewareInterface
{
/**
* @var SessionInterface
*/
private $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if (!$this->session->isStarted()) {
$this->session->start();
}
$response = $handler->handle($request);
$this->session->save();
return $response;
}
}