統一返回格式規範
// 成功
['status' => 'y', 'info' => '操作成功', 'data' => $result]
// 失敗
['status' => 'n', 'info' => '具體錯誤原因']
基礎控制器封裝
class BaseController extends Controller {
protected function ajaxReturn($data, $type = 'json') {
$this->ajaxReturn($data, $type); // ThinkPHP 內置方法
exit;
}
// 通用模型實例化
protected function D($name) {
return D($name); // ThinkPHP 快捷函數
}
}
通用新增方法
public function newData($modelName = '') {
if (!IS_POST) return;
$model = $this->D($modelName);
// create() 自動驗證、自動完成、令牌驗證
if (!$model->create()) {
$this->ajaxReturn(['status' => 'n', 'info' => $model->getError()]);
}
if ($model->add()) {
$this->ajaxReturn(['status' => 'y', 'info' => '新增成功']);
} else {
$this->ajaxReturn(['status' => 'n', 'info' => '寫入失敗,請重試']);
}
}
通用更新方法
public function update($modelName = '') {
if (!IS_POST) return;
$model = $this->D($modelName);
if (!$model->create()) {
$this->ajaxReturn(['status' => 'n', 'info' => $model->getError()]);
}
if ($model->save() !== false) { // save() 返回 0 也是成功
$this->ajaxReturn(['status' => 'y', 'info' => '更新成功']);
} else {
$this->ajaxReturn(['status' => 'n', 'info' => '更新失敗']);
}
}
通用刪除方法
public function delete($modelName = '') {
if (!IS_POST) return;
$id = I('post.id');
if (empty($id)) {
$this->ajaxReturn(['status' => 'n', 'info' => '缺少 ID 參數']);
}
$model = $this->D($modelName);
if ($model->delete($id) !== false) {
$this->ajaxReturn(['status' => 'y', 'info' => '刪除成功']);
} else {
$this->ajaxReturn(['status' => 'n', 'info' => '刪除失敗或記錄不存在']);
}
}
模型定義驗證規則(關鍵)
class UserModel extends Model {
protected $_validate = [
['username', 'require', '用戶名不能為空'],
['username', '', '用戶名已存在', self::EXISTS_VALIDATE, 'unique'],
['email', 'email', '郵箱格式不正確'],
['password', 'require', '密碼不能為空'],
['password', 'min_length[6]', '密碼至少6位'],
];
protected $_auto = [
['create_time', 'time', self::MODEL_INSERT, 'function'],
['update_time', 'time', self::MODEL_BOTH, 'function'],
['status', 1, self::MODEL_INSERT],
];
}
前端 AJAX 調用示例
// 新增
$.post('/User/newData/User', {username: 'Tom', email: 'tom@test.com', password: '123456'}, function(res) {
if (res.status === 'y') layer.msg(res.info, {icon: 1});
else layer.msg(res.info, {icon: 2});
}, 'json');
// 刪除
$.post('/User/delete/User', {id: 10}, function(res) { ... }, 'json');
避坑指南
save() 返回 0 表示「影響 0 行」但執行成功,判斷需用 !== false。
create() 會自動過濾非數據表字段,防止注入多餘數據。
- 批量刪除建議用
where('id', 'in', $ids)->delete(),單條刪除用 delete($id)。
- 生產環境關閉
APP_DEBUG,錯誤信息不直接輸出前端。