Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...