Add value to route before

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

example code:

$app->hook('slim.before', function () use ($app) {
    $env = $app->environment();
    $path = $env['PATH_INFO'];
    
    $uriArray = explode('/', $path);
    $dynamicvalue = 'value';
    if(array_key_exists($uriArray[1], array)) {
        $dynamicvalue = $uriArray[1];
        $path_trimmed = substr($path, strlen($dynamicvalue) + 1); 
        $env['PATH_INFO'] = $path_trimmed;
    }
  
});

i read about the middleware but i am not able to get correctly how to do it
can any one help me to do with slim 4