尝试在 Rest API 中实现 GET 方法,以查询用户状态,例如 GET user/:id/status
因此获取用户 ID #1 的状态将调用 /user/1/status
在配置中我有:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'v1/user'
],
'extraPatterns' => [
'GET status' => 'status',
],
'tokens' => [
'{id}' => '<id:\\w+>'
],
],
],
用户模型:
namespace api\modules\v1\models;
use \yii\db\ActiveRecord;
class User extends ActiveRecord {
/**
* @inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* @inheritdoc
*/
public static function primaryKey() {
return [ 'id' ];
}
}
用户控制器:
namespace api\modules\v1\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController {
public $modelClass = 'api\modules\v1\models\User';
public function actions() {
$actions = parent::actions();
unset(
$actions[ 'index' ],
$actions[ 'view' ],
$actions[ 'create' ],
$actions[ 'update' ],
$actions[ 'delete' ],
$actions[ 'options' ]
);
return $actions;
}
protected function verbs() {
return [
'status' => [ 'GET' ],
];
}
public function actionStatus( $id ) {
return 1;
}
}
但现在我不确定如何实际返回调用数据。