How to add middleware with instancing `on demand`

Hi. I have API & web routes:

$app->post('/api/action1', Action1::class);
$app->group('/admin', function(RouteCollectorProxy $group) {
    $group->get('/page1', Page1::class);
})
    ->add('csrf')
    ->add(TwigMiddleware::createFromContainer($app, Twig::class));

In dependencies Twig::class create CsrfExtension witch create Guard object. The last must use session storage to store csrf tokens. So, at finish I got cookie while request to api routes. In any case, it is wrong to create twig object on every api request…

So I need to some “lazy” init TwigMiddleware::createFromContainer($app, Twig::class), but have no idea how. I can’t use anonymous function because of
Return value of class@anonymous::handle() must be an instance of Psr\Http\Message\ResponseInterface, instance of Slim\Views\TwigMiddleware returned
error. How can I do this in right way?

You certainly pass Slim a Dependency Container. Let it do the instantiation work for you and register your middleware like this:

$container[ TwigMiddleware::class] = function ($dic) {
  $app = ...
  return TwigMiddleware::createFromContainer($app, Twig::class);
};

and in your route definition: push just the class name to the route middleware stack, like so:

$app->post( ...)->add(TwigMiddleware::class);

Big thanks, I move that anonymous function in dependencies.php and all work fine :+1: