URL rewriting with Yii framework

2019-08-05 01:07发布

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.

2条回答
狗以群分
2楼-- · 2019-08-05 01:31

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/'
    ),
),
查看更多
smile是对你的礼貌
3楼-- · 2019-08-05 01:40

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>'
查看更多
登录 后发表回答