Yii urlManager允许使用空参数的RESTful规则

时间:2011-12-02 04:39:10

标签: php url-routing yii

我目前有一条规则允许根据namebrandIdingredients查询几个不同的模型。此规则有效,除非我尝试为任何可选参数传入空值。我以为我使用了正确的RegEx,但显然没有。我试过了两个:

array('ws/service/query', 'pattern'=>'ws/service/query/<model:\w+>/(<name:\w+>)?/(<brand:\d+>)?/(<ingredients:.+>)?', 'verb'=>'GET'),

array('ws/service/query', 'pattern'=>'ws/service/query/<model:\w+>/<name:(\w+)?>/<brand:(\d+)?>/<ingredients:(.+)?>', 'verb'=>'GET'),

无济于事。当我输入查询字符串时:/ws/service/query/myModel///我得到PHP错误 - 未定义索引'模型'。但是当我使用像/ws/service/query/myModel/a/1/a这样的查询字符串时,我得到了所需的结果。

如何允许URL接受GET参数的空值?

以下是行动:

public function actionQuery()
    {
                $this->_checkAuth();

        switch ($_GET['model'])
                {
                        case 'dogFood':
                                $criteria = new CDbCriteria();
                                if ($_GET['name']) {
                                        $criteria->addSearchCondition('name_df', $_GET['name']);
                                }
                                if ($_GET['ingredients']) {
                                        $ingredientsArray = explode(',',$_GET['ingredients']);
                                        foreach ($ingredientsArray as $ingredient) {
                                                $criteria->addSearchCondition('ingredients_df', $ingredient);
                                        }
                                }
                                if ($_GET['brand']) {
                                        $criteria->addColumnCondition(array('brand_df' => $_GET['brand']));
                                }
                                $models = DogfoodDf::model()->findAll($criteria);
                                break;
                        default:
                                $this->_sendResponse(501, sprintf(
                                        'Error: Mode <b>query</b> is not implemented for model <b>%s</b>',
                                        $_GET['model']));
                                exit;
                }

                if (empty($models)) {
                        $this->_sendResponse(200,
                                sprintf('No items were found for model <b>%s</b>', $_GET['model']));
                }
                else {
                        $rows = array();

                        foreach ($models as $model) {
                                $rows[] = $model->attributes;
                        }

                        $this->_sendResponse(200, CJSON::encode($rows));
                }
    }

0 个答案:

没有答案