admin管理员组

文章数量:1355684

I am following the documentation of slim 4 middleware at Docs

I was able to implement the before middleware. But not sure how to implement after middleware. It says the DI should be used but the code in the doc is incomplete.

index.php:

<?php

use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;

use App\Middlewares\Globals\ExampleBeforeMiddleware;
use App\Middlewares\Globals\ExampleAfterMiddleware;

use Psr\Http\Message\ResponseFactoryInterface;


require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// Create Twig
// $twig = Twig::create(__DIR__ . '/../views', ['cache' => __DIR__.'/../cached']);
$twig = Twig::create(__DIR__ . '/../views', ['cache' => false]);

// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));

$app->add(new ExampleBeforeMiddleware());  // Working fine

require __DIR__.'/../routes/web.php';

$app->add(new ExampleAfterMiddleware()); // Throwing error


$app->run();

Afer middleware:

<?php

namespace App\Middlewares\Globals;

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

class ExampleAfterMiddleware implements MiddlewareInterface
{
    private ResponseFactoryInterface $responseFactory;

    public function __construct(ResponseFactoryInterface $responseFactory)
    {
        $this->responseFactory = $responseFactory;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Check some condition to determine if a new response should be created
        if (true) {
            // Create a new response using the response factory
            $response = $this->responseFactory->createResponse();
            $response->getBody()->write('New response created by middleware');
            
            return $response;
        }

        // Proceed with the next middleware
        return $handler->handle($request);
    }
}

Error message:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function App\Middlewares\Globals\ExampleAfterMiddleware::__construct(), 0 passed in

The error clearly says I need to pass the ResponseInterface into constructor. But it is not clear how to pass it.

I am following the documentation of slim 4 middleware at Docs

I was able to implement the before middleware. But not sure how to implement after middleware. It says the DI should be used but the code in the doc is incomplete.

index.php:

<?php

use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;

use App\Middlewares\Globals\ExampleBeforeMiddleware;
use App\Middlewares\Globals\ExampleAfterMiddleware;

use Psr\Http\Message\ResponseFactoryInterface;


require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// Create Twig
// $twig = Twig::create(__DIR__ . '/../views', ['cache' => __DIR__.'/../cached']);
$twig = Twig::create(__DIR__ . '/../views', ['cache' => false]);

// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));

$app->add(new ExampleBeforeMiddleware());  // Working fine

require __DIR__.'/../routes/web.php';

$app->add(new ExampleAfterMiddleware()); // Throwing error


$app->run();

Afer middleware:

<?php

namespace App\Middlewares\Globals;

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

class ExampleAfterMiddleware implements MiddlewareInterface
{
    private ResponseFactoryInterface $responseFactory;

    public function __construct(ResponseFactoryInterface $responseFactory)
    {
        $this->responseFactory = $responseFactory;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Check some condition to determine if a new response should be created
        if (true) {
            // Create a new response using the response factory
            $response = $this->responseFactory->createResponse();
            $response->getBody()->write('New response created by middleware');
            
            return $response;
        }

        // Proceed with the next middleware
        return $handler->handle($request);
    }
}

Error message:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function App\Middlewares\Globals\ExampleAfterMiddleware::__construct(), 0 passed in

The error clearly says I need to pass the ResponseInterface into constructor. But it is not clear how to pass it.

Share Improve this question edited Mar 30 at 12:59 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 30 at 2:33 Alaksandar Jesus GeneAlaksandar Jesus Gene 6,88713 gold badges59 silver badges92 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

Instead of responseFactory I used Response directly. It worked. Not sure if this approach has any cons

<?php

namespace App\Middlewares\Globals;

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

class ExampleAfterMiddleware implements MiddlewareInterface
{
    private ResponseFactoryInterface $responseFactory;

    // public function __construct(ResponseFactoryInterface $responseFactory) // commented out
    // {
    //     $this->responseFactory = $responseFactory;
    // }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Check some condition to determine if a new response should be created
        if (true) {
            // Create a new response using the response factory
            // $response = $this->responseFactory->createResponse(); // commented out this line
            $response = new \Slim\Psr7\Response(); // Added this line 

            $response->getBody()->write('New response created by middleware');
            
            return $response;
        }

        // Proceed with the next middleware
        return $handler->handle($request);
    }
}
$app->add(new ExampleAfterMiddleware());

In this code, you need ResponseFactoryInterface to make ExampleAfterMiddleware generate a response.

So you should set the DI container to automatically inject the object:

$responseFactory = new DefaultResponseFactory();
$app->add(new ExampleAfterMiddleware($responseFactory));

The error would be solved.

本文标签: How to implement after middleware in slim 4 php frameworkStack Overflow