如何在Slim Framework的特定路由上添加中间件

时间:2019-06-19 01:49:07

标签: php api slim

我正在使用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);
    }

    public static function log($request, $response, $next) {
        //Do stuff...
        return $next($request, $response);
    }
}

1 个答案:

答案 0 :(得分:1)

在这种情况下,问题在于该行为所有路由注册了中间件:

$app->add(function($request, $response, $next) use ($middlewareFunction) {

为单个路由注册中间件的工作方式如下:

$this->get('/', \App\Action\HomeIndexAction::class)
    ->add(MyMiddleware::class);

我会尝试像这样更改您的代码:

<?php

use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;

return function (App $app) {
    $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 = $args[0] ?? null;
        $endpoint = $args[1] ?? null;
        $controller = $args[2] ?? null;
        $routeMiddleware = $args[3] ?? null;

        // This line has changed
        $route = $app->{$verb}($endpoint, $controller);

        if (isset($routeMiddleware) && $routeMiddleware !== '') {
            $routeMiddleware = trim($routeMiddleware);

            $middlewares = explode('|', $routeMiddleware);

            foreach ($middlewares as $middlewareFunction) {
                // This line has changed
                $route->add(function ($request, $response, $next) use ($middlewareFunction) {
                    return Middleware::{$middlewareFunction}($request, $response, $next);
                });
            }
        }
    }
};