How to define route for module in itself?

When I tries to add routing for module in init() method it doesn’t work. But when we add same rules in config


'urlManager' => [ 'rules' => [here] ]

this works perfectly. Does yii2 have any posibility to set route rules in modules and config only included module class? Thanks!

Try this:




<?php


namespace something\xxx;


use yii\console\Application as ConsoleApplication;

use yii\web\GroupUrlRule;


class Module extends \yii\base\Module implements \yii\base\BootstrapInterface

{

    public $urlPrefix = 'xxx';


    /** @inheritdoc */

    public function bootstrap($app)

    {

        /** @var $module Module */

        if ($app->hasModule('xxx') && ($module = $app->getModule('xxx')) instanceof Module) {


            if ($app instanceof ConsoleApplication) {

                //$module->controllerNamespace = 'something\xxx\commands';

            } else {

                $rules = [

                    '' => 'default/index',

                    'something/<action:\w+>/<name:\w+>' => 'YourControllerID/<action>',

                    'something/<action:\w+>' => 'YourControllerID/<action>',

                ]

                $configUrlRule = [

                    'prefix' => 'xxx',

                    'rules' => $rules,

                ];


                if ($module->urlPrefix != 'xxx') {

                    $configUrlRule['routePrefix'] = 'xxx';

                }


                $app->get('urlManager')->rules[] = new GroupUrlRule($configUrlRule);

            }

        }

    }

}



Remember to add your module to web config:

‘bootstrap’ => [‘log’, ‘xxx’],

1 Like