Search code examples
phpslimslim-3

Create routes with controllers in Slim 3 like in Laravel 5


With the PHP framework Slim 3 in Routes, I did this:

// In routes :
$app->get('article/{id}-{slug}', function ($request, $response, $args) {
    $class = new Site\ArticleController($args);
    $class->show();
});

// In controllers :
public function show($args)
{
    $sql = "SELECT * FROM articles WHERE id = $args['id'] AND slug = $args['slug']";
    // ...
}

In Laravel 5 this coudl be written like:

// In routes :
Route::get('article/{id}-{slug}', 'Site\ArticleController@show');

// In controllers :
public function show($id, $slug)
{
    $sql = "SELECT * FROM articles WHERE id = $id AND slug = $slug";
    // ...
}

Can we do the same with Slim 3? I mean this:

$app::get('article/{id}-{slug}', 'Site\ArticleController@show');

Solution

  • You can structure Slim 3 routes similar to Laravel by doing something like this:

    <?php
    // In routes :
    $app->get('article/{id}-{slug}', '\Site\ArticleController:show');
    
    // In controllers :
    public function show($request, $response, $args)
    {
        $sql = "SELECT * FROM articles WHERE id = $args['id'] AND slug = $args['slug']";
        // ...
    }
    

    The Slim router now passes $request and $response in the first and second parameters and then any Route arguments you set in the last $args.

    I hope this helps! :)