我正在尝试在 Slim 中使用 Controller ,但一直出现错误
PHP 可捕获 fatal error :参数 1 传递给
TopPageController::__construct() 必须是 ContainerInterface 的一个实例,
给定的 Slim\Container 实例
我的index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require 'settings.php';
spl_autoload_register(function ($classname) {
require ("../classes/" . $classname . ".php");
});
$app = new \Slim\App(["settings" => $config]);
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write("Welcome");
return $response;
});
$app->get('/method1', '\TopPageController:method1');
$app->run();
?>
我的 TopPageController.php
<?php
class TopPageController {
protected $ci;
//Constructor
public function __construct(ContainerInterface $ci) {
$this->ci = $ci;
}
public function method1($request, $response, $args) {
//your code
//to access items in the container... $this->ci->get('');
$response->getBody()->write("Welcome1");
return $response;
}
public function method2($request, $response, $args) {
//your code
//to access items in the container... $this->ci->get('');
$response->getBody()->write("Welcome2");
return $response;
}
public function method3($request, $response, $args) {
//your code
//to access items in the container... $this->ci->get('');
$response->getBody()->write("Welcome3");
return $response;
}
}
?>
谢谢。我正在使用 Slim 3。
最佳答案
您的代码似乎是基于位于 http://www.slimframework.com/docs/objects/router.html 的 Slim 3 文档其中不包含避免抛出异常所需的所有代码。
基本上,您有两种选择来让它发挥作用。
选项 1:
在 index.php
中导入命名空间,就像为 Request
和 Response
所做的那样:
use \Interop\Container\ContainerInterface as ContainerInterface;
选项 2:
将 TopPageController 的构造函数更改为:
public function __construct(Interop\Container\ContainerInterface $ci) {
$this->ci = $ci;
}
长话短说
抛出异常的原因是 Slim\Container
类正在使用 Interop\Container\ContainerInterface
接口(interface)(参见源代码):
use Interop\Container\ContainerInterface;
由于 Slim\Container
是对 Pimple\Container
的扩展,因此对于您的 Controller 方法,以下内容应该都是有效的(有效的)类型声明:
public function __construct(Pimple\Container $ci) {
$this->ci = $ci;
}
...甚至...
public function __construct(ArrayAccess $ci) {
$this->ci = $ci;
}
关于php - Slim Controller 问题 : must be an instance of ContainerInterface, 给定的 Slim\\Container 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37906363/