Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 routes definition in modules

Tags:

php

routes

yii2

Is there any solution to add routes from module configuration?

Example. We have main config where we describe

'components' => [
    'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                'rules' => require(FILE_PATH_CONFIG_ENV . '_routes.php') // return array
    ],
]

in each module we load custom config file with private parameters

public function loadConfig($sFileName = 'main', $sFolderName = 'config')
{
    Yii::configure($this, require($this->getBasePath() . DS . $sFolderName . DS . $sFileName . '.php'));

    return $this;
}

Config file

return [
    'components' => [
        'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'rules' => [
                '/admin' => '/admin/index/index',
            ]
        ]
    ]
];

And now I need somehow merge current config (main for web application) with config loaded from module. In end I want describe in module config routes only for this module and use them for pretty urls (user friendly url). How can I do this one? This examples not working when I create url /admin/index/index, it shows me /admin/index/index but I want /admin as mentioned in module rules.

like image 928
user1954544 Avatar asked Jan 14 '15 23:01

user1954544


People also ask

What is module in yii2?

Modules are self-contained software units that consist of models, views, controllers, and other supporting components. End users can access the controllers of a module when it is installed in application. For these reasons, modules are often viewed as mini-applications.


2 Answers

So I did this way (this is full answer for a question).

Create Bootstrap class special for module.

namespace app\extensions;

use yii\base\BootstrapInterface;

/**
 * Class ModuleBootstrap
 *
 * @package app\extensions
 */
class ModuleBootstrap implements BootstrapInterface
{
    /**
     * @param \yii\base\Application $oApplication
     */
    public function bootstrap($oApplication)
    {
        $aModuleList = $oApplication->getModules();

        foreach ($aModuleList as $sKey => $aModule) {
            if (is_array($aModule) && strpos($aModule['class'], 'app\modules') === 0) {
                $sFilePathConfig = FILE_PATH_ROOT . DS . 'modules' . DS . $sKey . DS . 'config' . DS . '_routes.php';

                if (file_exists($sFilePathConfig)) {
                    $oApplication->getUrlManager()->addRules(require($sFilePathConfig));
                }
            }
        }
    }
}

Create route file in module folder (/modules/XXX/config/_routes.php)

return [
    '/sales'                            => '/sales/index/index',
    '/sales/company'                    => '/sales/company/index',
    '/sales/company/view/<sID:\d+>'     => '/sales/company/view',
    '/sales/company/update/<sID:\d+>'   => '/sales/company/update',
    '/sales/company/delete/<sID:\d+>'   => '/sales/company/delete',
];

Add boostrap to main config file

$aConfig = [
    // some code
    'bootstrap' => [
        // some code
        'app\extensions\ModuleBootstrap',
    ],
    'modules' => [
        // some code
        'sales' => ['class' => 'app\modules\sales\SalesModule']
    ]
]

return $aConfig;

That's it. We can define routes only in module 'route' config.

PS: I don't like detection if (is_array($aModule) && strpos($aModule['class'], 'app\modules') === 0) (I mean NOT 'debug', 'log', 'gii' or other native Yii2 modules) maybe someone can suggest better solution?

like image 143
user1954544 Avatar answered Oct 30 '22 16:10

user1954544


And this will be more clean and reliable. I have found this on Yii2's github repo here.

<?php
namespace backend\modules\webmasters;

use Yii;
use yii\base\BootstrapInterface;

class Module extends \yii\base\Module implements BootstrapInterface
{
    public $controllerNamespace = 'backend\modules\webmasters\controllers';

    public function init()
    {
        parent::init();
        // initialize the module with the configuration loaded from config.php
        Yii::configure($this, require(__DIR__ . '/config/main.php'));
    }

    /**
     * @inheritdoc
     */
    public function bootstrap($app)
    {
        $app->getUrlManager()->addRules([
            [
                'class' => 'yii\web\UrlRule', 
                'pattern' => $this->id, 
                'route' => $this->id . '/tools/index'
            ],
            [
                'class' => 'yii\web\UrlRule', 
                'pattern' => $this->id . '/<controller:[\w\-]+>/<action:[\w\-]+>', 
                'route' => $this->id . '/<controller>/<action>'
            ],
        ], false);
    }
}

and just configure your main.php config file's bootstrap section as

'bootstrap' => [
    'log',
    'webmasters'
]
'modules' => [
    'webmasters' => [
        'class' => 'backend\modules\webmasters\Module'
     ]
]
like image 29
Anil Chaudhari Avatar answered Oct 30 '22 14:10

Anil Chaudhari