bereal's avatar

Nested Route Groups and namespace

Hi there.

I just started to use Lumen and wondering if there is a better way to fix this:

as we know in bootstrap/app.php the routes.php file is included in the following way:

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../app/Http/routes.php';
});

So everything works good if I define simple routes in routes.php:

$app->get('/public/airports',           'AirportsController@index');

But if I define another group with prefixes in routes.php, I cannot use namespace-less controller names and have to use full notation :

$app->group(['prefix' => 'public'], function ($app) {
    $app->get('/test', 'App\Http\Controllers\AirportsController@index');
});

or adding namespace parameter :

$app->group(['prefix' => 'public', 'namespace' => 'App\Http\Controllers'], function ($app) {
    
    $app->get('/test', 'AirportsController@index');
});

is there a way to avoid that?

0 likes
4 replies
phildawson's avatar

I don't think it's the prefix specifically that does it, defining the group again resets the group attributes.

$app->group([], function ($app) {
    $app->get('public/airports', 'AirportsController@index'); // Class AirportsController does not exist
});
1 like
phildawson's avatar
Level 26

is there a way to avoid that?

Nope. I've just had a check and annoyingly Lumen doesn't merge the attributes. So although it's functioning correctly it's not helpful.

Lumen

    public function group(array $attributes, Closure $callback)
    {
        $this->groupAttributes = $attributes;

        ..
    }

Laravel

    public function group(array $attributes, Closure $callback)
    {
        $this->updateGroupStack($attributes);

        ..
    }
    protected function updateGroupStack(array $attributes)
    {
        if (! empty($this->groupStack)) {
            $attributes = $this->mergeGroup($attributes, end($this->groupStack));
        }

        $this->groupStack[] = $attributes;
    }

    public static function mergeGroup($new, $old)
    {
        $new['namespace'] = static::formatUsesPrefix($new, $old);

        $new['prefix'] = static::formatGroupPrefix($new, $old);

        if (isset($new['domain'])) {
            unset($old['domain']);
        }

        $new['where'] = array_merge(
            isset($old['where']) ? $old['where'] : [],
            isset($new['where']) ? $new['where'] : []
        );

        if (isset($old['as'])) {
            $new['as'] = $old['as'].(isset($new['as']) ? $new['as'] : '');
        }

        return array_merge_recursive(array_except($old, ['namespace', 'prefix', 'where', 'as']), $new);
    }
1 like
bereal's avatar

Ok, thanks.

Not very convenient, but doesn't seem as a critical bug

chimit's avatar

If somebody still has this problem here are some good news. In Lumen 5.3.2 it was finally fixed.

2 likes

Please or to participate in this conversation.