简体   繁体   English

用Yii框架重写URL

[英]URL rewriting with Yii framework

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) 为此,我在main.php(配置文件夹)中编写了这样的规则

'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 这意味着内部“ xyz”将根据规则作为参数传递给我的FoodController的actionIndex

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 我面临的问题是在同一个类中还有另一个方法称为actionItems,当我使用URL时

www.example.com/food/items

it calls the actionIndex and passes "items" as a parameter 它调用actionIndex并传递“ items”作为参数

Any idea on how to solve this? 关于如何解决这个问题的任何想法?

Thanks in advance. 提前致谢。

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>'URL与'/ food / action'URL区别开来,例如:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM