Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Default Route Arguments in Slim

DZone's Guide to

Default Route Arguments in Slim

Interested in learning the basics of this Ruby template engine? In this article, we show you how to set up a Hello World message using Slim.

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

A friend of mine recently asked how to do default route arguments and route specific configuration in Slim, so I thought I'd write up how to do it.

Consider a simple Hello route:

$app->get("/hello[/{name}]", function ($request, $response, $args) {
    $name = $request->getAttribute('name');
    return $response->write("Hello $name");
})

This will display "Hello " for the URL /hello and "Hello Rob" for the URL /hello/Rob.

If we wanted a default of "World," we can set an argument on the Route object that is returned from get() (and all the other routing methods):

$app->get("/hello[/{name}]", function ($request, $response, $args) {
    $name = $request->getAttribute('name');
    return $response->write("Hello $name");
})->setArgument('name', 'World');

This works exactly as you would expect.

The route arguments don't have to be a placeholder and you can set multiple route arguments. For example:

$app->get("/hello[/{name}]", function ($request, $response, $args) {
    $name = $request->getAttribute('name');
    $foo = $request->getAttribute('foo');
    return $response->write("Hello $name, foo = $foo");
})->setArguments([
'name' => 'World,
'foo' => 'bar',
]);

Now, we have a foo attribute in our request, which is a per-route configuration option that you can do with as you wish - e.g. setting acl rules like this:

$app->get("/users", App\HelloAction::class)->setArgument("role", "userAdministrator");

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:
web dev ,slim framework ,ruby

Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}