Cacomania: Using some of the new Slim 2.3.0 features in the bookmark app

Cacomania

Using some of the new Slim 2.3.0 features in the bookmark app

Guido Krömer - 19. July 2013 - Tags:

Recently I wrote about building a RESTful API with the Slim Framework. This Framework has just reached Version 2.3.0 with some nice new features. I am going to show some of them, by refactoring the bookmark API using the new features of Slim.

Route Groups

New in Slim 2.3.0 is the availability of grouping routes this avoids having several routes beginning with the same prefix. Take a look at the snippet from the old code below, each route begins with the /bookmark prefix.

$app->get('/bookmark', function () use ($db, $app) {
    ...
});

$app->get('/bookmark/:id', function ($id) use ($db, $app) {
    ...
});

$app->post('/bookmark', function () use ($db, $app) {
    ...
});

$app->put('/bookmark/:id', function ($id) use ($db, $app) {
    ...
});

$app->delete('/bookmark/:id', function ($id) use ($db) {
    ...
});

This routes can be combined by their prefix using the group() method, each sub route only defines the differences like routes with an id and routes without an id. More complex sub routes are possible, too.

$app->group('/bookmark', function () use ($app) {
    $app->get('', function () use ($app) {
        ...
    });

    $app->get('/:id', function ($id) use ($app) {
        ...
    });

    $app->post('', function () use ($app) {
        ...
    });

    $app->put('/:id', function ($id) use ($app) {
        ...
    });

    $app->delete('/:id', function ($id) use ($app) {
        ...
    });
});

Resource locator

A Slim application contains out of routes and closures which are called when a route matches. Since a closure has its own scope, resources must passed to the closure within the use statement. A database connection was passed to each closure for example. Using the resource locator it is sufficient passing only the Slim instance to each closure.

A resource can be a single value, a closure returning a value, a singleton or override an existing one like the request resource for example. I converted the database connection passed to each request closure into a singleton. This has two advantages the connection is only created/fetched if the resource gets used and ensures that only one connection exists. The first parameter of the singleton() method defines the resource name and the second one is the closure creating the resource.

$app->container->singleton('db', function () {
    return new PDO('sqlite:db.sqlite3');
});

Conclusion

The new version contains some really cool features and many more I had not used when refactoring this tutorial app. Besides those features large parts of the framework had been refactored like the logging, which is now PSR compliant.

There is a branch of the bookmark app using the new features at GitHub. I hope you enjoyed my small posting, feel free to leave a comment.