Sunil Dabhi
Sunil Dabhi

Reputation: 99

Slim 3 middleware setting parameters not getting

settings.php file code

return [
'settings' => [
    'displayErrorDetails' => true, // set to false in production
    'addContentLengthHeader' => false, // Allow the web server to send the content-length header
    'encryption_key' => 'key1',
    'jwt_secret' => 'secret1',
    'db' => [
        'servername' => 'localhost',
        'username' => 'user',
        'password' => 'pwd',
        'dbname' => 'db',
    ],
],];

index.php file code

$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);

$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/",
"passthrough" => ["/login"],
"secret" => $this->jwt_secret,
"secure" => false,
"error" => function ($request, $response, $arguments) {
    $data["status"] = "error";
    $data["message"] = $arguments["message"];
    return $response
        ->withHeader("Content-Type", "application/json")
        ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}]));

i am getting error: Using $this when not in object context in

how can i get settings attribute in middleware?

Upvotes: 0

Views: 445

Answers (1)

odan
odan

Reputation: 4952

In this context $this should be the Slim Container object.

The settings are stored as an array and can be accessed like this:

$app->add(function (Request $request, Response $response, $next) {
    /* @var Container $this */
    $settings = $this->get('settings');

    $jwtSecret = $settings['jwt_secret'];

    // Do something...

    return $next($request, $response, $next);
});

Upvotes: 2

Related Questions