Yii2 Dynamic URL Routing Rules

元气小坏坏 提交于 2019-12-18 04:24:27

问题


I want to set Dynamic Routing for url in Cms pages in yii2. When i add Cms page i will add page alias aboutus,faq,management etc , these alias will saved in db .

When i give URL rule static it will work ,[check code below]

'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',
),
        ], 

But i want add url rule in dynamically .

I need add all dynamic page alias in config/main.php URL rule in yii2 Please help me.


回答1:


You can edit you routing rules during bootstrapping process.

First create bootstrapping class by implementing yii\base\BootstrapInterface

Under Your components directory create a file called 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
}     

}

Now in your configuration file (web.php in config folder) in $config array add above class under bootstrap option

'bootstrap' => [
    .... // other bootstrap options 
    'app\components\DynaRoute', // add this line 
],



回答2:


In addition to ck_arjun's answer, you can pass parameter to route as an ID. For example, if you want redirect "/aboutus" to "/site/page/id/2".

Replace:

$routeArray[$row->alias] = 'YOUR_ORIGINAL_URL'

in

$routeArray[] = ['class' => 'yii\web\UrlRule', 'pattern' => $row->alias, 'route' => $row->route, 'defaults' => ['id' => $row->id]];


来源:https://stackoverflow.com/questions/36056440/yii2-dynamic-url-routing-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!