Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

php - Yii2 Dynamic URL Routing Rules

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can edit you routing rules during bootstrapping process.

First create bootstrapping class by implementing yiiaseBootstrapInterface

Under Your components directory create a file called DynaRoute.php

<?php

 namespace appcomponents;

 use Yii;
 use yiiaseBootstrapInterface;
 use appmodelsCms;  // 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 
    'appcomponentsDynaRoute', // add this line 
],

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...