Base Middleware problem

Hello,

I’m trying to use Middleware in Slim v3.12.

I have a base middleware class (that other middleware classes can extend) like this:

use Interop\Container\ContainerInterface;
abstract class BaseMiddleware {
    protected $container;

    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }
}

The purpose of this middleware is to get and share the $container.

In my other ExampleMiddleware, I extend the BaseMiddleware class like this:

class ExampleMiddleware extends BaseMiddleware {
    public function __invoke($request, $response, $next) {
        /* some code */
        return $next($request, $response);
    }
}

Finally, in my routes, I added ExampleMiddleware like this:

$app->get('/', function($request, $response) {
   return 'Example';
})->add(new ExampleMiddleware());

But, I get this error:

Fatal error : Uncaught ArgumentCountError: Too few arguments to function Middleware\BaseMiddleware::__construct(), 0 passed in …/app/routes.php on line 6 and exactly 1 expected in…/app/Middleware/BaseMiddleware.php…

The error disappears If I modify the route like so:

$app->get('/', function($request, $response) {
   return 'Example';
})->add(new ExampleMiddleware($container));

But ExampleMiddleware does not have a constructor.

Why is this happening?

Any help would be appreciated.

But ExampleMiddleware does not have a constructor.
Why is this happening?

ExampleMiddleware extends from BaseMiddleware and BaseMiddleware has a constructor. This means that ExampleMiddleware also has a constructor due to inheritance.

1 Like

Thanks, @odan. It’s okay now.