1

Hi Folks i upgrading my slim framework from slim 2 to slim 4 for older project
for one route i added the one value before route using slim 2 slim.before in index.php

example code:

$app->hook('slim.before', function () use ($app) {
    $env = $app->environment();
    $path = $env['PATH_INFO'];
    
    // spliting the route and adding the dynamic value  to the route
    $uriArray = explode('/', $path);
    $dynamicvalue = 'value';
    if(array_key_exists($uriArray[1], array)) {
        $dynamicvalue = $uriArray[1];
        //we are trimming the api route
        $path_trimmed = substr($path, strlen($dynamicvalue) + 1); 
        $env['PATH_INFO'] = $path_trimmed;
    }
  
});

i read about the add beforemiddleware but cannot able find correct way to add it and i cannot able to find the replacement for $app->environment();

i want to append the dynamic value directly to route

for example

i have one route like this

https://api.fakedata.com/fakeid

by using the above route splitting code i appending the value route using slim.before in slim 2

for example take the dynamic value as test

the route will be

https://api.fakedata.com/test/fakeid

the response of the both api will be same we want to just add value to the route

can any one help me how to do with slim 4

4

1 回答 1

2

我假设您需要和PATH_INFO到环境,以便您以后可以在路由回调中引用它。您可以添加一个中间件以将属性添加到$request路由回调接收:

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Psr7\Response;

class PathInfoMiddleware {
    public function __invoke(Request $request, RequestHandler $handler) : Response {
        $info = 'some value, path_trimmed for example...'; // this could be whatever you need it to be
        $request = $request->withAttribute('PATH_INFO', $info);
        return $handler->handle($request);
    }
}

// Add middleware to all routes
$app->add(PathInfoMiddleware::class);

// Use the attribute in a route
$app->get('/pathinfo', function(Request $request, Response $response){
    $response->getBody()->write($request->getAttribute('PATH_INFO'));
    return $response;
});

现在访问/pathinfo给出以下输出:

一些值,例如 path_trimmed ......

于 2022-01-12T20:02:40.993 回答