Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor long php file of routes (I'm using Slim Framework)

Tags:

php

slim

I am using the Slim Framework for a simple crud-style application. My index.php file has become quite long and unwieldy with all the different routes. How can I clean up / refactor this code? For example I have code like the following for all the different routes and GET, POST, PUT, DELETE etc.

$app->get("/login", function() use ($app)
{//code here.....});
like image 930
weaveoftheride Avatar asked Jul 17 '14 09:07

weaveoftheride


1 Answers

What I like to do is group routes, and for each group, I create a new file under a subdir called routes. To illustrate with some example code from the Slim docs:

index.php:

$app = new \Slim\Slim();
$routeFiles = (array) glob(__DIR__ . DIRECTORY_SEPARATOR . 'routes' . DIRECTORY_SEPARATOR . '*.php');
foreach($routeFiles as $routeFile) {
  require_once $routeFile;
}
$app->run();

routes/api.php:

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

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

        // Get book with ID
        $app->get('/books/:id', function ($id) {

        });

        // Update book with ID
        $app->put('/books/:id', function ($id) {

        });

        // Delete book with ID
        $app->delete('/books/:id', function ($id) {

        });

    });

});

You can even do this for multiple levels, just be sure you don't overcomplicate yourself for this.

You can also do this for hooks off course.

like image 83
Ruben Vincenten Avatar answered Oct 21 '22 11:10

Ruben Vincenten