2
\$\begingroup\$

i'm trying to create a url router system, for educational purposes, that has a similar usage like Laravel has, but i'm curious about how i can register the routes like laravel does (with single calls to static methods), here's my "conceptual" code that i made using a TDD approach:

        $Route = new Route;
        $Route
        ->setUri('users/[i:id]')
        ->setMethod('GET')
        ->setCallback(function () {
            return 'get user';
        })
        ->setMiddleware([
            App\Http\Middlewares\Auth::class,
            App\Http\Middlewares\Permission::class
        ])
        ->setName('users.show');

        $Route2 = new Route;
        $Route2
        ->setUri('orders')
        ->setMethod('POST')
        ->setCallback('OrdersController@create')
        ->setMiddleware([
            App\Http\Middlewares\Auth::class
        ])
        ->setName('orders.post');

        $Router = new Router;
        $Router->addRoute($Route);
        $Router->addRoute($Route2);
        // if the route is matched this methods are called
        // $Router->handleMiddlewares();
        // $Router->handleCallback();
        $Router->run();

1 - there's a better approach about how to encapsulate the route object creation to a simple/shorter way? eg: in Laravel we can map routes like this:

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback)->name('foo');

2 - should the router class be responsible for filtering routes (regex rules etc), handling callbacks and middlewares?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.