slimphp / Slim

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
http://slimframework.com
MIT License
11.94k stars 1.95k forks source link

Middleware Arguments Access #1594

Closed AdamGold closed 8 years ago

AdamGold commented 8 years ago

Hi, how can I access route's args in my middleware? Here's how I am adding the middleware:

$route->add(function ($request, $response, $next) use ($mw) {
    return $mw->middlewareFunc($request, $response, $next);
});

Currently, in order to get the arguments, I do this manually (it works, but I wish this was built in in Slim):

$path = strtok($_SERVER['REQUEST_URI'], '?');
$path = str_replace(SUB_FOLDER, '', $path);
$pathArr = array_values(array_filter(explode('/', $path)));
/* remove from args array the known routes (user, category, product etc.)
* loop through all routes and delete all the non-variables (non {}) */
foreach ($this->routes as $route) {
    $routeUrl = array_filter(explode('/', $route['url']));
    foreach ($routeUrl as $key => $url) {
        if ($url[0] != '{') { // this is not an arg
            if (isset($this->prefixes[$key])) {
                if (!in_array($url, $this->prefixes[$key])) { // we don't already have this prefix
                    $this->prefixes[$key][] = $url;
                }
            } else {
                $this->prefixes[$key][] = $url;
            }
        }
    }
}
$args = [];
foreach ($pathArr as $key => $value) {
    /* remove prefixes from url in the right position */
    if (!isset($this->prefixes[$key])) {
        $args[] = $value;
    } else {
        if (!in_array($value, $this->prefixes[$key])) {
            $args[] = $value;
        }
    }
}

return $args;
silentworks commented 8 years ago

Like this:

$route = $request->getAttribute('route');
$route->getArguments();
// or
$route->getArgument('argumentName');
AdamGold commented 8 years ago

Great, thank you very much.

dopesong commented 8 years ago

@silentworks I think we should mention this in docs, because it's common question.

silentworks commented 8 years ago

@dopesong good point, you wanna PR it or I will add it later on in the week.

geggleto commented 8 years ago

@silentworks https://github.com/slimphp/Slim-Website/pull/68/files

silentworks commented 8 years ago

Done