6

I want to group paths under one common path. I found in the Yii2 documentation that this can be achieved with the GroupUrlRule() class. I can not understand where to set it. I tried to sat it as a rule to the urlManager in confing/web.php but nothing happened.

SO-user
  • 1,458
  • 2
  • 21
  • 43
bozhidarc
  • 834
  • 1
  • 11
  • 25

2 Answers2

7

Imagine that you have some module. Your confing/web.php file might look like this:

'components' => [
    'urlManager' => [
        'class' => 'yii\web\UrlManager',
        'showScriptName' => false,
        'enablePrettyUrl' => true,
        'rules' => [
            [
                'class' => 'yii\web\GroupUrlRule',
                'prefix' => 'module',
                'rules' => [
                    '/' => 'controller/index',
                    'create' => 'controller/create',
                    'edit' => 'controller/edit',
                    'delete' => 'controller/delete',
                ],
            ],
        ],
    ],
]

Now, by URL hostname.com/module will be called 'module/controller/index'.

xfg
  • 638
  • 9
  • 11
5

You can do it in Bootstrap file. Example:

project/Bootstrap.php

namespace app;

use yii\base\BootstrapInterface;
use yii\web\GroupUrlRule;

class Bootstrap implements BootstrapInterface
{
    public $urlRules = [
        'prefix' => 'admin',
        'rules' => [
            'login' => 'user/login',
            'logout' => 'user/logout',
            'dashboard' => 'default/dashboard',
        ],
    ];

    public function bootstrap($app)
    {
        $app->get('urlManager')->rules[] = new GroupUrlRule($this->urlRules);
    }
}

project/config/web.php

return [
    // ...
    'bootstrap' => [
        'log',
        'app\Bootstrap',
    ],
    // ...
]

P.S. Bootstrap files are extremely useful with modular application structure. It is much more clear to configure module's routes inside the module's folder. For that purpose just create Bootstrap file for every module in its folder. But don't forget to update bootstrap section of your application config file.

Aleksei Akireikin
  • 1,999
  • 17
  • 22
  • Shouldn't the Module class implement BootstrapInterface? [doc-2.0: adding rules](http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#adding-rules) – Brainfeeder Jan 27 '17 at 14:13
  • @Brainfeeder it depends. If both `Module` and `Bootstrap` files are small it makes sense, otherwise I prefer store them separately. – Aleksei Akireikin Feb 21 '17 at 09:10
  • Ok, that makes sense. Do I load all module bootstraps in the main config? Or is it Ok to load them in a module config? – Brainfeeder Feb 23 '17 at 19:56
  • Personally I prefer load all module bootstraps in the main config, but it’s a matter of personal taste. – Aleksei Akireikin Feb 24 '17 at 16:43