【发布时间】:2018-05-19 14:39:05
【问题描述】:
我正在尝试实现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;
}
}
【问题讨论】: