URL rewriting with Yii framework

坚强是说给别人听的谎言 提交于 2019-12-24 12:36:34

问题


I have a url like

www.example.com/food/xyz

for which I have written a rule like this in the main.php (config folder)

'urlManager'=>array(
    'urlFormat'=>'path',
    'showScriptName'=>false,
    'caseSensitive'=>false,
    'rules'=>array(
        '/food/<name:\w+>/' => 'food/index/',
        '<controller:\w+>/<id:\d+>'=>'<controller>/view',
        '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
        '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
    ),
),

This means that internally "xyz" will be passed as a parameter to the actionIndex of my FoodController according to the rule

class FoodController extends Controller
{
    public function actionIndex($name){
        //some code here
    }

    public function actionItems(){
        //some code here
    }
}

The problem i'm facing is that I have another method in the same class called actionItems and when I use the URL

www.example.com/food/items

it calls the actionIndex and passes "items" as a parameter

Any idea on how to solve this?

Thanks in advance.


回答1:


Your first rule should be for the items

'/food/items'=>'food/items',
'/food/<name:\w+>/' => 'food/index/',

Alternatively, I would rather use an alias to split the use of the controller such that all 'food'/<:name>' urls are differentiated from '/food/action' urls for example:

'/food/<name:\w+>/' => 'food/index/',
'/foods/<action:\w+>' => 'food/<action>'



回答2:


Try this, just change order:

'urlManager'=>array(
    'urlFormat'=>'path',
    'showScriptName'=>false,
    'caseSensitive'=>false,
    'rules'=>array(
        '<controller:\w+>/<id:\d+>'=>'<controller>/view',
        '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
        '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
        '/food/<name:\w+>/' => 'food/index/'
    ),
),


来源:https://stackoverflow.com/questions/16152956/url-rewriting-with-yii-framework

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