使用 Composer 的 Slim 框架无法按预期工作(Class 未找到)

Slim framework not working as expected using Composer (Class not found)

你能帮帮我吗?我面临一个奇怪的问题。 首先,我正在使用 composer:

下载这个 https://github.com/tuupola/slim-jwt-auth
composer require tuupola/slim-jwt-auth

之后,我创建了一个名为 php 的文件:teste.php:

require 'vendor/autoload.php';

$app = new Slim\App;

$app->add(new \Slim\Middleware\JwtAuthentication([
    "secret" => "teste",
    "callback" => function ($options) use ($app) {
        $app->jwt = $options["decoded"];
    }
]));

$app->get("/user", function () {
    print_r($app->jwt);
});

$app->run();

现在,我收到了这个错误:

PHP message: PHP Fatal error:  Uncaught Error: Class 'Slim\App' not found

这没有意义,因为我正确使用了作曲家

我该如何解决?我花了很多时间尝试自己解决这个问题,但我失败了。谢谢!

首先,您需要将 Slim 框架实际添加到您的 Composer 包中。您可以通过 运行:

composer require slim/slim

关于您的其他问题,您为中间件使用的构造函数不正确。应该是:new Tuupola\Middleware\JwtAuthentication.

你的完整代码应该如下:

require 'vendor/autoload.php';

$app = new Slim\App;

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "secret" => "teste",
    "callback" => function ($options) use ($app) {
        $app->jwt = $options["decoded"];
    }
]));

$app->get("/user", function () {
    print_r($app->jwt);
});

$app->run();