I'm trying to create a custom middleware class and can't seem to call extend \\Slim\\Middleware
because it's not found.
This is my index.php
<?php
require __DIR__ . '/../vendor/autoload.php';
session_start();
// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);
// Register middleware
require __DIR__ . '/../src/middleware.php';
// Run app
$app->run();
This is my middleware.php
<?php
require_once("tester_auth.php");
$app->add(new TestAuth());
This is my tester_auth.php which is the custom middleware file
<?php
use Slim\Middleware;
class TestAuth extends \Slim\Middleware {
public function __construct() {
//Define the urls that you want to exclude from Authentication, aka public urls
$this->whiteList = array('\/login');
}
public function deny_access() {
$res = $this->app->response();
$res->status(401);
}
public function isPublicUrl($url) {
$patterns_flattened = implode('|', $this->whiteList);
$matches = null;
preg_match('/' . $patterns_flattened . '/', $url, $matches);
return (count($matches) > 0);
}
public function call() {
//Get the token sent from jquery
$tokenAuth = $this->app->request->headers->get('Authorization');
//We can check if the url requested is public or protected
if ($this->isPublicUrl($this->app->request->getPathInfo())) {
//if public, then we just call the next middleware and continue execution normally
$this->next->call();
} else {
$this->deny_access();
}
}
}
It successfully gets to my TestAuth but gives me the error Class 'Slim\\\\Middleware' not found in /var/www/html/src/tester_auth.php on line 6
...
Edit:
At first, I was having this issue because my composer.json didn't have middleware installed but I have since updated it and it's there now but still having the same issue..
"require": {
"php": ">=5.5.0",
"slim/slim": "^3.8",
"slim/php-view": "^2.0",
"slim/middleware": "*",
"monolog/monolog": "^1.17"
}
Try to restart your HTTP server (ngixn, PHP web server,..) in case it caches some PHP.
BTW, slim/middleware is for Slim 2. , but you are using 3. .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.