Create middleware to replace slim.before hook

Hello all! , i am upgrading my old application from slim 2 to slim 3

in my application i added the one value to the route before the output buffer using slim.before hook

for example code and route

$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 have one route like this it returns json response data

if i hit the route with adding extra parameter in the search bar to route like this

it will also return same response as the response which return from first route
i achieved this by adding the en parameter using slim.before hook in slim 2

from slim 3 hooks is deprecated , and replaced with middleware

how can we achieve this in slim 3 or 4 using middleware

can anyone help me with the code

Thank you!

It’s hard to guess how your source code looks like. So it’s even harder to help here. Could you please show us your current routes for this example?

@odan Added the example code please let me know if any other requirements

I would suggest a different approach, that should behave like you expected.

Instead of using a middleware for it, I would try to create a route with a placeholder for the additional parameters.

Have you tried this?

1 Like