Ivan Ivan - 1 month ago 15
reST (reStructuredText) Question

Slim 3 Framework - Should I be using Route Groups for my API?

Should I be using this structure...

require 'vendor/autoload.php';
$app = new \Slim\App;

$app->get('/books', 'getBooks');
$app->get('/books/{id}', 'getBook');

$app->run();

function getBooks() {
// Return list of books
}

function getBook($id) {
// Return a single book
}


Or this "Route Groups" one?

require 'vendor/autoload.php';
$app = new \Slim\App;

$app->group('/books', function () use ($app) {
$app->get('', function ($req, $res) {
// Return list of books
});

$app->get('/{id:\d+}', function ($req, $res, $args) {
// Return a single book
});
});

$app->run();


What is the better way? The former seems much cleaner. I am relatively new, so I am unaware of the pros and cons.

Answer

Generally, you use route groups to organise similar resources or content so you can visibly see their relationship in the code. Route groups are also helpful if you need to put any special conditions such as middleware on a specific group. For example, You might have an administrator section on your website, and you want to make sure that the user is actually an administrator before accessing the controller.

$app->get('panel/admin', 'Admin/DashboardController:index')->add($adminAuth);
$app->get('panel/admin/users', 'Admin/UserController:index')->add($adminAuth);
$app->post('panel/admin/users', 'Admin/UserController:create')->add($adminAuth);

Obviously, it would make more sense to group these routes together because they share similar traits. If you ever need to change anything about these traits in the future (like the type of middleware), you would only have to do it once.

$app->group('/panel', function() use ($app) {
    $app->group('/admin', function() use ($app) {
        $app->get('', 'Admin/DashboardController:index');
        $app->get('/users', 'Admin/UserController:index');
        $app->post('/users', 'Admin/UserController:create');

    })->add($adminAuth);
})->add($userAuth);

It's also helpful if you would ever want to expand the use case of that specific URI, so lets say you want to roll out a new feature in the panel that regular users can use.

$app->group('/panel', function() use ($app) {

    $app->group('/admin', function() use ($app) {

        $app->get('', 'Admin/DashboardController:index');
        $app->get('/users', 'Admin/UserController:index');
        $app->post('/users', 'Admin/UserController:create');

    })->add($adminAuth);


    $app->get('', 'DashboardController:index');

})->add($userAuth);

Although it isn't a great deal of importance, it is just good practice to layout all your code as organised as possible, and route groups allow you to do this.