URL rewriting with Yii framework

2019-08-05 01:32发布

问题:

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