Slim controller issue : must be an instance of ContainerInterface, instance of Slim\\Container given
Your code seems to be based on the Slim 3 documentation at http://www.slimframework.com/docs/objects/router.html which does not contain all the required code to avoid the Exception being thrown.
You basically have two options to make it work.
Option 1:
Import the namespace in your index.php
, just like it is being done for Request
and Response
:
use \Interop\Container\ContainerInterface as ContainerInterface;
Option 2:
Change the constructor of the TopPageController to:
public function __construct(Interop\Container\ContainerInterface $ci) {
$this->ci = $ci;
}
TL;DR
The reason the Exception is thrown is that the Slim\Container
class is using the Interop\Container\ContainerInterface
interface (see the source code):
use Interop\Container\ContainerInterface;
Since Slim\Container
is extending Pimple\Container
, the following should all be valid (working) type declarations for your controller's method:
public function __construct(Pimple\Container $ci) {
$this->ci = $ci;
}
...or even...
public function __construct(ArrayAccess $ci) {
$this->ci = $ci;
}
Based on a later change in Slim3 (from version 3.12.2 to 3.12.3) a slightly different ContainerInterface is required. This changes \Interop\
to \Psr\
. Add the following on top of you code or change the existing use
:
use Psr\Container\ContainerInterface;
Or change the constructor:
public function __construct(\Psr\Container\ContainerInterface $container)
{
$this->container = $container;
}
Just paste the below code in your controller
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Interop\Container\ContainerInterface as ContainerInterface;
Your controller's construct should look like the one below
public function __construct(ContainerInterface $container) {
parent::__construct($container);
}
I think you are making mistake in giving namespace in controller for ContainerInterface
.