Reputation: 135
I'm trying to use a middleware
in my Slim route
but i have an error:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Api\Middleware\Auth::__invoke(), 2 passed
Index File
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Api\Middleware\Auth;
require __DIR__ . '../../../vendor/autoload.php';
$app = AppFactory::create();
$app->add(new Auth);
$app->get('/', function (Request $request, Response $response, $args) {
$response->getBody()->write("Start Project");
return $response;
});
$app->run();
Middleware File
<?php
namespace Api\Middleware;
class Auth {
public function __invoke($request, $response, $next) {
echo "Middleware";
return $next($request, $response);
}
}
I'm reading and copying the docs but cannot fix that error.
Upvotes: 0
Views: 1046
Reputation: 6144
Based on the documentation you've linked the middleware in Slim is either the function that takes two arguments, or a object with __invoke
magic method that takes two arguments. The arguments passed are Psr\Http\Message\ServerRequestInterface
and Psr\Http\Server\RequestHandlerInterface
.
Your implementation of middleware is expecting 3 arguments.
It should look like this:
class Auth {
public function __invoke($request, $handler) {
echo "Middleware";
return $handler->handle($request);
}
}
Upvotes: 2