Slim 3 Framework. Should I use route groups for my API?

Should I use 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 is this the “Route Group” 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(); 

Which is better? The first seems a lot cleaner. I am relatively new, so I do not know the pros and cons.

+5
source share
1 answer

Typically, you use route groups to organize similar resources or content so that you can see their relationship in the code. Route groups are also useful if you need to specify any special conditions, such as middleware for a specific group. For example, your website may have an administrator section, and you must ensure 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 be wiser to combine these routes, because they have similar features. If you ever need to change anything about these traits in the future (for example, a type of middleware), you will need to do this only 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 is also useful if you ever want to expand the use of this particular URI, so let's say that you want to use a new function in the panel that ordinary 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); 

Despite the fact that this does not really matter, it’s best to place all your code as organized as possible, and route groups allow you to do this.

+9
source

Source: https://habr.com/ru/post/1239381/


All Articles