我正在使用 Slim Framework 构建一个 API,我编写了一个脚本来创建路由并动态添加它的中间件。问题是由于某种原因,这些路线被应用到应用程序中的每条路线。如何仅在一条路由上应用中间件?
这是 route.cfg 文件
#[HTTP Verb] [Route] [Controller::method] [middleware|middleware]
GET /usuario/autenticar UsuarioController:autenticar log
GET /usuario/listar[/{id}] UsuarioController:listar log|autenticar
GET /usuario/encerrarSessao UsuarioController:encerrarSessao log|autenticar
POST /usuario/cadastrar UsuarioController:cadastrar log|autenticar
PUT /usuario/editar UsuarioController:editar log|autenticar
DELETE /usuario/deletar UsuarioController:deletar log|autenticar
这是读取路由文件的脚本
<?php
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
return function (App $app) {
$container = $app->getContainer();
$routesFile = file(__DIR__ . '/routes.cfg');
foreach ($routesFile as $fileLine) {
$fileLine = str_replace("\n", "", $fileLine);
$fileLine = preg_replace('/\s+/', ' ', $fileLine);
$args = explode(' ', $fileLine);
if (strpos($fileLine, '#') !== false || count($args) < 3) continue;
$verb = array_key_exists(0, $args) ? $args[0] : null;
$endpoint = array_key_exists(1, $args) ? $args[1] : null;
$controller = array_key_exists(2, $args) ? $args[2] : null;
$routeMiddleware = array_key_exists(3, $args) ? $args[3] : null;
$app->{$verb}($endpoint, "$controller");
if (isset($routeMiddleware) && strlen($routeMiddleware) > 0) {
$routeMiddleware = trim($routeMiddleware);
$middlewares = explode('|', $routeMiddleware);
foreach ($middlewares as $middlewareFunction) {
$app->add(function($request, $response, $next) use ($middlewareFunction) {
return Middleware::{$middlewareFunction}($request, $response, $next);
});
}
}
}
};
这是我的中间件类
<?php
use Slim\App;
class Middleware {
public static function autenticar($request, $response, $next) {
//Do stuff...
return $next($request, $response);
}
江户川乱折腾