Search code examples
phpcomposer-phpslim

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


Can you help me? I'm facing a strange issue. First, I'm downloading this https://github.com/tuupola/slim-jwt-auth using composer:

composer require tuupola/slim-jwt-auth

After that, I created a php file called: 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();

And now, I'm getting this error:

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

This does not make sense, since I used the composer correctly

How can I solve that? I spent many hours trying fix this by myself and I failed. Thank you!


Solution

  • First of all, you need to actually add the Slim framework to your Composer package. You can do this by running:

    composer require slim/slim
    

    Regarding your other problem, the constructor you're using for the middleware is incorrect. It should be: new Tuupola\Middleware\JwtAuthentication.

    Your complete code should be as follows:

    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();