我正在尝试实施https://www.slimframework.com/docs/v3/objects/router.html所描述的Allow Slim to instantiate the controller
部分。这样做时,我收到以下错误:
传递给Michael \ Test \ HomeController :: __ construct()的参数1必须 是Slim \ ContainerInterface的实例,Slim \ Container的实例 给予,召唤 /var/www/slimtest/vendor/slim/slim/Slim/CallableResolver.php上线 93
认为它可能与命名空间有关,我也在\
命名空间中尝试但是也遇到了同样的错误。
https://www.slimframework.com/docs/v3/objects/router.html上的文档是否不正确,HomeController的构造函数参数声明类型应该是Slim\Container
,还是我做错了,Slim\ContainerInterface
是否正确?
<?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();
家庭控制器
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;
}
}
答案 0 :(得分:2)
\Slim\ContainerInterface
不存在(请参阅here)。查看\Slim\Container
您需要使用的接口Interop\Container\ContainerInterface
的实现,或者您可以使用Slim实现\Slim\Container
作为类型参数。