Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the Yii2 GroupUrlRule() class

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.

like image 271
bozhidarc Avatar asked Jun 19 '14 14:06

bozhidarc


2 Answers

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'.

like image 148
xfg Avatar answered Oct 21 '22 12:10

xfg


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.

like image 23
Aleksei Akireikin Avatar answered Oct 21 '22 14:10

Aleksei Akireikin