Yii2动态URL路由规则

Bij*_*u s 3 php url-routing yii2

我想Dynamic Routing在yii2中的Cms页面中设置url.当我添加Cms页面时,我将添加页面别名aboutus,faq,management等,这些别名将保存在db中.

当我给URL规则静态时它会工作,[检查下面的代码]

'urlManager' => [               
            'showScriptName' => false,  
            'enablePrettyUrl' => true,  
            //'enableStrictParsing' => true,
            'rules'=>array(
'aboutus'=>'cms/index/1',
'faq'=>'cms/index/2',
'termacondition'=>'cms/index/3',
'management'=>'cms/index/4',
),
        ], 
Run Code Online (Sandbox Code Playgroud)

但我想动态添加网址规则.

我需要在yii2中的config/main.php URL规则中添加所有动态页面别名.请帮帮我.

ck_*_*jun 9

您可以在引导过程中编辑路由规则.

首先通过实现创建bootstrapping类 yii\base\BootstrapInterface

在Your components目录下,创建一个名为DynaRoute.php的文件

<?php

 namespace app\components;

 use Yii;
 use yii\base\BootstrapInterface;
 use app\models\Cms;  // assuming Cms is the Model class for table containing aliases
 class DynaRoute implements BootstrapInterface
 {
     public function bootstrap($app)
     {

        $cmsModel = Cms::find()
            ->all(); // customize the query according to your need
        routeArray = [];
        foeach($cmsModel as $row) { // looping through each cms table row
            $routeArray[$row->alias] = 'YOUR_ORIGINAL_URL'; // Adding rules to array on by one
        }
        $app->urlManager->addRules($routeArray);// Append new rules to original rules
}     
Run Code Online (Sandbox Code Playgroud)

}

现在在你的配置文件(配置文件夹中的web.php)$config数组中添加bootstrap选项下面的类

'bootstrap' => [
    .... // other bootstrap options 
    'app\components\DynaRoute', // add this line 
],
Run Code Online (Sandbox Code Playgroud)