2

这是 api 网址。

/api/web/v1/users/123

通过 id 查找用户。如何将规则更改为 find by token,而不是 by id

这是一个规则:

            [
                'class' => 'yii\rest\UrlRule',
                'controller' => ['v1/users'],
                'tokens' => [
                    '{id}' => '<id:\\w+>'

                   // this does not work  
                   // '{token}' => '<token:\\w+>'
                ],
            ],
4

1 回答 1

1

{id}定义为令牌的是内置yii\rest\ViewAction使用的令牌,代码如下:

class ViewAction extends Action
{
    /**
     * Displays a model.
     * @param string $id the primary key of the model.
     * @return \yii\db\ActiveRecordInterface the model being displayed
     */
    public function run($id)
    {
        $model = $this->findModel($id);
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id, $model);
        }

        return $model;
    }
}

$this->findModel($id)在yii\rest\Action下定义,它使用主键查找模型。如果您需要使用不同的标记{token}并在与其主键不同的属性中找到您的模型,那么您需要覆盖控制器内的视图操作。

'{token}' => '<token:\\w+>'这是添加到规则时应该工作的示例:

class UserController extends ActiveController
{
    ...
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['view']);
        return $actions;
    }

    public function actionView($token){
        $modelClass = $this->modelClass;
        $model = $modelClass::find()->where(['token' => $token])->one();

        if ($model === null)
            throw new \yii\web\NotFoundHttpException("Uknown user having $token as token");

        return $model;
    }

}

另请注意,您需要更改$patterns以支持新引入的模式。您的最终规则可能如下所示:

'rules' => [
    [
        'class' => 'yii\rest\UrlRule', 
        'controller' => ['v1/users'],  
        'tokens' => [
            '{id}' => '<id:\\w+>',
            '{token}' => '<token:\\w+>'
        ]
        'patterns' => [
            'PUT,PATCH {id}' => 'update',
            'DELETE {id}' => 'delete',
            // {token} is assigned to $token when redirecting to view
            'GET,HEAD {token}' => 'view',
            'POST' => 'create',
            'GET,HEAD' => 'index',
            '{id}' => 'options',
            '' => 'options',
        ],
    ],
]
于 2016-06-01T09:52:43.297 回答