chen7david
chen7david

Reputation: 109

nested php slim 3 middleware

I am creating an API and need to implement the following functionality. 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.

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.

Upvotes: 1

Views: 398

Answers (1)

Zamrony P. Juhara
Zamrony P. Juhara

Reputation: 5262

First $ifa can be simplified as

$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).

To make it $ifa as class instead of anonymous function, you can declare it like this

<?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);

Upvotes: 2

Related Questions