Laravel: is it possible to dynamically set a controller for a route?

So, let's say I have a simple controller that processes books.

App\Http\Controllers\SimpleBooksController

Inside routes.phpI will register a route for him:

Route::get('books/{id}','SimpleBooksController@doSimpleStuff');

But the world of books is not so simple. Therefore, I would like to have another controller that handles the really complex material of the book.

In my head, I suppose something like this would be really helpful:

class ComplexBooksController extends SimpleBooksController

In this way, routes that are not explicitly handled by the child class are returned to the parent class.

Now let's say each book knows whether it is complicated or not: $book->isComplex

And I would like to do something like this

if (!$book->isComplex) {
    // route 'books/{id}' to SimpleBooksController@doSimpleStuff
} else {
    // route 'books/{id}' to ComplexBooksController@doComplexStuff
}

So how can this be done?

* edit *

The way I'm handling this right now is to install the controllers in route.php statically, but let them listen to parameterized routes:

Route::get('books/simple/{id}', 'SimpleBooksController@doSimpleStuff');
Route::get('books/complex/{id}', 'ComplexBooksController@doComplexStuff');
+4
2

, .

, isComplex:

Route::get('books/{id}', function($id) {

    $result = DB::select('SELECT is_complex FROM books WHERE id = ?', [$id]);

    if (empty($result)) abort(404);

    $book = $result[0];

    if ($book->is_complex)
        return redirect()->action('SimpleBooksController@doSimpleStuff');
    else
        return redirect()->action('ComplexBooksController@doComplexStuff');

});
+2

. .

- .

, , .

:

Route::get('books/{id}','BooksController@doSimpleStuff');

:

class BooksController extends Controller
{
      public function showBook($book)
      {
           if ($book->isComplex()) {
                $this->dispatch(new HandleComplexBook($book));
           } else {
                $this->dispatch(new HandleSimpleBook($book));
           }
      }

}

:

class HandleComplexBook extends Command implements SelfHandling {

    protected $book;

    public function __construct(Book $book)
    {
        $this->book = $book;
    }

    public function handle()
    {
        // Handle the logic for a complex book here
    }

}

class HandleSimpleBook extends Command implements SelfHandling {

    protected $book;

    public function __construct(Book $book)
    {
        $this->book = $book;
    }

    public function handle()
    {
        // Handle the logic for a simple book here
    }

}
+2

All Articles