gpt4 book ai didi

php - Slim Controller 问题 : must be an instance of ContainerInterface, 给定的 Slim\\Container 实例

转载 作者:可可西里 更新时间:2023-11-01 12:28:17 25 4
gpt4 key购买 nike

我正在尝试在 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 中导入命名空间,就像为 RequestResponse 所做的那样:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com