依赖项中的严重错误找不到控制器

时间:2019-07-09 12:13:36

标签: php slim

我遇到了Slim Application Error:

Class 'Slim\App\Controllers\MainController' not found

这似乎与其他帖子相同,除了它们的前面没有'Slim'。我认为这就是失败的原因。

项目结构

/src
    /Controllers
        MainController.php
    /vendor
    /public
        index.php

composer.json

{
"require": {
    "slim/slim": "^3.12"
},

"autoload": {
    "psr-4" : {
        "App\\" : "src/"
    }
}

}

index.php

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

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

$configuration = [
    'settings' => [
    'displayErrorDetails' => true,
],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);

require_once('../settings.php');
require_once('../dependencies.php');
require_once('../routes.php');

$app->run();

dependencies.php

use Slim\App;
use Slim\Container;
use App\Controllers;

$container = $app->getContainer();

$container['MainController'] = function ($c)
{
    return new App\Controllers\MainController;
};

/src/Controllers/MainController.php

namespace App\Controllers;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

class MainController
{
public function search(Request $request, Response $response, $args)
{
    $response->write("Hello");

    return $response;
}
}

2 个答案:

答案 0 :(得分:0)

始终使用完整的类名作为容器ID。

示例

use App\Controllers\MainController;
// ...

$container[MainController::class] = function ($c)
{
    return new MainController();
}

答案 1 :(得分:0)

dependencies.php 中,您编写了> gender Var1 Freq 1 f 1 2 m 2 ,而use App\Controllers;是一个名称空间,而不是类名。使用App\Controllers关键字时,您需要命名一个类,就像在useuse Slim\App;中所做的那样。

这是您的代码的修改版本,可以正常运行:

index.php

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

src / Controllers / MainContrloller.php

<?php
require __DIR__ . '/../vendor/autoload.php';

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\App;
use Slim\Container;
use App\Controllers\MainController;

$app = new \Slim\App;
$container = $app->getContainer();

$container['MainController'] = function ($c)
{
    return new MainController;
};

$app->get('/', 'MainController');

$app->run();