Yii2 RESTful API 基础与架构概览
本实例深入解析 Yii2 框架中 RESTful API 的运行机制,旨在为开发者提供参考与实践指导。
Yii2 内置了对 RESTful API 的原生支持,仅需进行简短的配置,即可快速为现有的 Model 暴露标准的 RESTful 接口服务。
本文将通过拆解 rest 模块的源码逻辑,简明扼要地阐述 Yii2 构建 RESTful API 的底层原理,并结合具体案例展示如何通过自定义开发,实现对关联模型的 RESTful 操作。
~ 符号在本文中代表继承(extends from)关系。
| | rest/ | | |-Action.php ~ `\yii\base\Action` | | |-Controller.php ~ `\yii\web\Controller` | | | |-ActiveController.php ~ `rest\Controller` | | |-Serializer.php ~ `yii\base\Component` | | |-UrlRule.php ~ `yii\web\CompositeUrlRule` | | |-CreateAction.php ~ `rest\Action` | | |-DeleteAction.php ~ `rest\Action` | | |-IndexAction.php ~ `rest\Action` | | |-OptionsAction.php ~ `rest\Action` | | |-UpdateAction.php ~ `rest\Action` | | |-ViewAction.php ~ `rest\Action`
1. rest/Controller ~ \yii\web\Controller
Controller 作为 RESTful API 控制器的基类,承担着核心调度职责。
在一个完整的 API 请求生命周期中,它依次执行以下五个关键步骤:
① 解析响应的内容格式 ② 校验 HTTP 请求方法 ③ 验证用户访问权限 ④ 实施速率限制 ⑤ 格式化最终响应数据
use yii\filters\auth\CompositeAuth;
use yii\filters\ContentNegotiator;
use yii\filters\RateLimiter;
use yii\web\Response;
use yii\filters\VerbFilter;
/**
* Controller is the base class for RESTful API controller classes.
*
* Controller implements the following steps in a RESTful API request handling cycle
* 1. Resolving response format (see [[ContentNegotiator]]);
* 2. Validating request method (see [[verbs()]]).
* 3. Authenticating user (see [[\yii\filters\auth\AuthInterface]]);
* 4. Rate limiting (see [[RateLimiter]]);
* 5. Formatting response data (see [[serializeData()]])
behaviors
contentNegotiator
verbFilter
authenticator
rateLimiter
afterAction
serializeData Yii::createObject($this->serializer)->serialize($data)
verbs []
*/
class Controller extends \yii\web\Controller
{
public $serializer = 'yii\rest\Serializer';
public $enableCsrfValidation = false;
public function behaviors()
{
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
'verbFilter' => [
'class' => VerbFilter::className(),
'actions' => $this->verbs(),
],
'authenticator' => [
'class' => CompositeAuth::className(),
],
'rateLimiter' => [
'class' => RateLimiter::className(),
],
]
}
public function verbs()
{
return [];
}
public function serializeData($data)
{
return Yii::createObject($this->serializer)->serialize($data);
}
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
return $this->serializeData($result);
}
}
2. rest/ActiveController ~ rest/Controller
ActiveController 专门用于实现与 ActiveRecord 数据进行交互的一系列 RESTful 方法。
其操作的 ActiveRecord 类名由 modelClass 属性指定,需满足 yii\db\ActiveRecordInterface 接口规范。
默认情况下,它支持以下标准操作方法:
* - `index`: 获取模型列表 * - `view`: 返回单个模型的详细信息 * - `create`: 创建新模型 * - `update`: 更新现有模型 * - `delete`: 删除现有模型 * - `options`: 返回允许的 HTTP 方法列表
若需禁用某些默认动作,可通过重写 actions() 方法并移除对应的 action 配置来实现。
若要新增自定义动作,同样需要重写 actions() 方法,在数组末尾追加新的 action class 或 action method。
需注意,新增动作时必须同时重写 verbs() 方法,以明确声明该动作所支持的 HTTP Method。
此外,还需覆盖 checkAccess() 方法,用于判断当前用户是否有权执行特定的动作。
基于上述原理,重新梳理 Controller 的设计逻辑。
class ActiveController extends Controller
{
public #modelClass;
public $updateScenario = Model::SCENARIO_DEFAULT;
public $createScenario = Model::SCENARIO_DEFAULT;
public function init()
{
parent::init();
if($this->modelClass == null){
throw new InvalidConfigException('The "modelClass" property must be set.');
}
}
public function actions()
{
return [
'index' => [
'class' => 'app\controllers\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'view'...
'create'...
'update'...
'delete'...
'options'...
];
}
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' =>['GET', 'HEAD'],
'create' =>['POST'],
'update' =>['PUT', 'PATCH'],
'delete' =>['DELETE'],
];
}
public function checkAccess($action, $model=null, $params = [])
{
}
}
接下来,我们将构建一个继承自 rest\ActiveController 的 News 控制器示例。
namespace app\controllers;
use app\controllers\rest\ActiveController; #刚才这个AC,我从yii/rest下面拷贝了一份出来
class NewsController extends ActiveController
{
public $modelClass ='app\models\News';
}
仅做上述基础配置已足以运行 rest\ActiveController 内置的默认方法。 下面将演示如何覆盖这些方法,以实现更复杂的定制功能。
class NewsController extends ActiveController
{
public $modelClass = 'app\models\News';
#定制serializer
#public $serializer = 'yii\rest\Serializer';
public $serializer = [
'class' => 'app\controllers\rest\Serializer',
'collectionEnvelope' => 'items',
];
public function behaviors()
{
$be = ArrayHelper::merge(
parent::behaviors(),
[
'verbFilter' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
...
]
],
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
]
],
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'text/html' => Response::FORMAT_HTML,
]
],
'access' => [
'class' => AccessControl::className(),
'only' => ['view'],
'rules' => [
[
'actions' => ['view'],
'allow' => false,
'roles' => ['@'],
],
],
]
],
);
return $be;
}
public function checkAccess()
{
}
}
3. 定制 Actions
若需对 Actions 进行大幅修改,建议复制一份代码独立维护,避免直接使用原始的 yii\rest\XXXAction 命名空间,以防升级冲突。
本文以实现对 related models(关联模型)进行 CURD 操作为目标,进行深度定制改造。
Action
在逐一定制各个 Action 之前,先审视其基类 rest\Action,其核心在于 findModel 方法的实现。
class Action extend \yii\base\Action
{
public $modelClass;
public $findModel;
public $checkAccess;
public function init()
{
if($this->modelClass == null) {
throw new InvalidConfigException(get_class($this). '::$modelClass must be set');
}
}
public function findModel($id)
{
if($this->findModel !== null) {
return call_user_func($this->findModel, $id, $this);
}
$modelClass = $this->modelClass;
$keys = $modelClass::primaryKey();
if(count($keys) > 1) {
$values = explode(',', $id);
if..
} elseif($id !== null) {
$model = $modelClass::findOne($id);
}
if(isset($model)){
return $model;
}else {
throw new NotFoundHttpException("Object not found: $id");
}
}
}
view
view 动作无需改动,因为 Model 自身具备 getRelated 机制来处理关联查询。
class ViewAction extend Action
{
public function run($id)
{
$model = $this->findModel($id);
if($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
}
}
update
public function run($id)
{
/* @var $model ActiveRecord */
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
$model->scenario = $this->scenario;
$model->load(Yii::$app->getRequest()->getBodyParams(), '');
$model->save();
return $model;
}
经过改造后,需确保 update 动作能够正确处理关联模型的更新逻辑。
public function run($id)
{
/* @var $model ActiveRecord */
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
$model->scenario = $this->scenario;
/*
*
* x-www-form-urlencoded key=>value
* image mmmmmmmm
* link nnnnnnnnnn
* newsItem[title]=>ttttttttttt , don't use newsItem["title"]
* newsItem[body]=>bbbbbbbbbbb
* don't use newsItem=>array("title":"tttttt","body":"bbbbbbb")
* don't use newsItem=>{"title":"ttttttt","body":"bbbbbbbb"}
*
*/
$newsItem = Yii::$app->getRequest()->getBodyParams()['newsItem'];
/*
Array
(
[title] => ttttttttttt
[body] => bbbbbbbbbbb
)
*/
$model->newsItem->load($newsItem, '');
#$model->newsItem->load(Yii::$app->getRequest()->getBodyParams(), '');
#print_R($model->newsItem);exit;
#print_R($model->newsItem);exit;
if($model->save())
{
$model->load(Yii::$app->getRequest()->getBodyParams(), '');
$model->newsItem->save();
}
return $model;
}
此处暂略 newsItem save 失败时的异常处理逻辑,后续可根据实际需求补充。
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。