dimanche 30 octobre 2022

How do Laravel route groups work under the hood?

I was wondering how is this working under the hood:

Route::group(['prefix' => 'parent'], function() {
    Route::get('/child', 'MyController@myMethod');
});

I don't understand how is Laravel associating the routes definitions in the anonymous function to the parent group.

Something like this would have made much more sense:

Route::group(['prefix' => 'parent'], function($group) {
    $group->get('/child', 'MyController@myMethod');
});

I tried diving into what happens under the hood through a debugger, and I noticed that in Illuminate\Routing\Router.php this happens:

protected function loadRoutes($routes)
{
    if ($routes instanceof Closure) {
        $routes($this);
    } else {
        (new RouteFileRegistrar($this))->register($routes);
    }
}

The anonymous function that contains our routes definitions is called and $this gets passed to it, altho our anonymous function doesn't accept any argument, so why passing $this to it?

Aucun commentaire:

Enregistrer un commentaire