尝试在Rest API中实现GET方法,以查询用户状态,例如获取用户/: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;
}
}
但现在我不确定如何实际返回呼叫数据。
答案 0 :(得分:1)
$user = User::findOne($id);
if ($user)
return Json::encode(['success'=>true, 'data'=>$user->status]);
else
return Json::encode(['success'=>false, 'message'=>"Can't find user"]);