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.
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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With