user1032531
user1032531

Reputation: 26331

What is the correct interface for Slim's container?

I am trying to implement the Allow Slim to instantiate the controller portion described by https://www.slimframework.com/docs/v3/objects/router.html. When doing so, I get the following error:

Argument 1 passed to Michael\Test\HomeController::__construct() must be an instance of Slim\ContainerInterface, instance of Slim\Container given, called in /var/www/slimtest/vendor/slim/slim/Slim/CallableResolver.php on line 93

Thinking it might have been namespace related, I also tried in the \ namespace but got the same error.

Is the documentation on https://www.slimframework.com/docs/v3/objects/router.html incorrect and should HomeController's constructor argument declaration type be Slim\Container, or am I doing something wrong and Slim\ContainerInterface is correct?

<?php
namespace Michael\Test;

error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);

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

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App();
$container = $app->getContainer();
//$container['view'] = function ($c) {};

//Question.  Do I need to use the fully qualified class name???
$app->get('/', \Michael\Test\HomeController::class . ':home');
//$app->get('/', '\Michael\Test\HomeController:home');

$app->run();

Home Controller

namespace Michael\Test;
class HomeController
{
    protected $container;

    // constructor receives container instance
    public function __construct(\Slim\ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}

Upvotes: 0

Views: 823

Answers (1)

jmattheis
jmattheis

Reputation: 11135

\Slim\ContainerInterface doesn't exist (see here). Looking at the implementation of \Slim\Container the interface you need to use is Interop\Container\ContainerInterface or you can just use the Slim implementation \Slim\Container as type parameter.

Upvotes: 3

Related Questions