简体   繁体   English

嵌套php slim 3中间件

[英]nested php slim 3 middleware

I am creating an API and need to implement the following functionality. 我正在创建一个API,需要实现以下功能。 Some roots need to be accessible to users that are: 用户需要访问某些根目录:

  1. List item 项目清单
  2. not loged in 尚未登录
  3. logged in 登录
  4. logged in and are premium users 登录并且是高级用户
  5. logged in and are premium users with x amount of points. 已登录,并且是具有x点数的高级用户。

For this reason I chose to use slim groups. 因此,我选择使用苗条的组。 Mind you, I'm not sure that this is the proper usage for group middle ware, but this is what I did. 请注意,我不确定这是否适用于组中间件,但这就是我所做的。

<?php 

    $ifa = function($request, $response, $next){
        $a=true;
        if ($a) {
            $request = $request->withAttribute('foo', 'bar');
            $response = $next($request, $response);
        }
        return $response;
    };

    $ifb = function($request, $response, $next){
        $b=true;
        if ($b) {
            $response = $next($request, $response);
        }
        return $response;
    };


    $ifc = function($request, $response, $next){
        $c=true;
        if ($c) {
            $response = $next($request, $response);
        }
        return $response;
    };

    $app->group('',function() use ($app, $ifb,$ifc){
        $app->get('/home', 'AuthController:home')->setName('home');
        $app->group('',function() use ($app,$ifc){
            $app->get('/school', 'AuthController:school');

            $app->group('',function() use ($app){
                $app->get('/farm', 'AuthController:farm');
            })->add($ifc);

        })->add($ifb);

    })->add($ifa);

I would like to separate my middleware code (named functions or classes) from my routes. 我想将中间件代码(命名为函数或类)与路由分开。 Even though this set up currently works, I would prefer to work with classes, what would be a cleaner way of writing my code? 即使此设置当前可行,我还是更喜欢使用类,哪种更干净的代码编写方式呢? I would appreciate any suggestions. 我将不胜感激任何建议。

First $ifa can be simplified as 第一个$ifa可以简化为

$ifa = function($request, $response, $next){
    $request = $request->withAttribute('foo', 'bar');
    return $next($request, $response);
};

$ifb and $ifc are useless and can be omitted and removed from route as they are essentially doing nothing (CMIIW). $ifb$ifc是无用的,可以将其省略并从路由中删除,因为它们实际上什么都不做(CMIIW)。

To make it $ifa as class instead of anonymous function, you can declare it like this 要使其成为类而不是匿名函数的$ifa ,可以这样声明

<?php

class Ifa
{
    public function __invoke($request, $response, $next)
    {
        $request = $request->withAttribute('foo', 'bar');
        return $next($request, $response);
    };

}

and in routes declaration 并在路线声明中

$app->group('/', function() {
    //do something here
})->add(Ifa::class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM