## 簡介
<br>
本章通過`api`完成文章新增。
<br>
## 編輯控制器
<br>
編輯`~/api/modules/v1/controllers/TitleController.php`
<br>
```
<?php
namespace?api\modules\v1\controllers;
use?api\models\Title;
use?yii\base\Exception;
use?yii\helpers\ArrayHelper;
use?yii\helpers\Json;
use?yii\helpers\VarDumper;
class?TitleController?extends?\yii\web\Controller
{
????public?$enableCsrfValidation?=?false;
????private?$code?=?200;
????private?$message?=?'success';
????private?$data?=?null;
????public?function?actionCreate()
????{
????????//接收并格式化數據
????????$data?=?\Yii::$app->request->getRawBody();
????????$data?=?Json::decode($data);
????????//構建DAO
????????$dao?=?new?\frontend\models\dao\Title();
????????$dao->title?=?ArrayHelper::getValue($data,?'title',?null);
????????$dao->author?=?ArrayHelper::getValue($data,?'author',?null);
????????$dao->date?=?date('Y-m-d',?time());
????????$dao->text?=?ArrayHelper::getValue($data,?'text',?null);
????????$dao->create_time?=?date('H:m:s',?time());
????????$dao->status?=?mt\_rand(1,?3);
????????//插入
????????$res?=?$dao->save();
????????//異常處理
????????if?(!$res)?{
????????????\Yii::error(VarDumper::dumpAsString($res));
????????????throw?new?Exception('新增出錯');
????????}
????????$this->data?=?$dao->toArray();
????????return?[
????????????'code'????=>?$this->code,
????????????'message'?=>?$this->message,
????????????'data'????=>?$this->data
????????];
????}
}
```
<br>
這里你會發現IDE標識了`use?api\models\Title`,查看文件發現`gii`生成的命名空間為`app\models`,這里需要變更過來。
<br>
`api`的調試,推薦使用`postman`,[postman百度網盤下載](https://pan.baidu.com/s/1dEMMD2L#list/path=%2F)。
<br>
后續默認使用`postman`進行調試。
<br>
## 測試結果
<br>
傳參及返回值展示
<br>

<br>