最近在写接口,很多方法都具有相同的部分,比如最开始的输入检查,过程中的异常捕捉,结果的格式输出。这样每个方法都有很多重复的代码,不符合DRY(Do not Repeat Yourself),首先写的不开心,然后不方便管理,容易出错。想着有什么好的办法可以将这些东西改写一下。于是想到了下面这种解决办法。
public function predictEdit(Request $request)
{
$result = GeneralService::cloak($request,[
'predict' => 'required|integer',
'title' => 'required|max:200',
// 更多验证规则
], function()use($request){
$predict_id = $request->get('predict');
$title = $request->get('title');
$predict = PlanePredict::find($predict_id);
$user_id = $request->get('user_id');
if (!$predict) {
throw new \Exception('predict not found', '2020');
}
$update_data = [
'title' => $title,
// 更多更新数据
];
$log_data = [
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s')
// 更多日志信息
];
$result = DB::transaction(function()use($predict, $update_data, $log_data){
$result = $predict->update($update_data);
Log::create($log_data);
return $result;
});
});
return $result;
}
public static function cloak($request, $validation, $func)
{
try {
$validator = Validator::make($request->all(), $validation);
if ($validator->fails()) {
info("\n"."------------------------------"."\n");
info($validator->errors());
info("\n"."------------------------------"."\n");
throw new \Exception("invalid input", "2020");
}
$result = $func();
return Response::json([
'header' => [
'status' => '1000',
'message' => 'success'
],
'data' => $result
]);
} catch (\Exception $e) {
info(__METHOD__."\n".$e->getTraceAsString());
info("\n"."------------------------------"."\n");
info($e->getCode()." | ".$e->getMessage());
return Response::json([
'header' => [
'status' => $e->getCode(),
'message' => $e->getMessage()
],
'data' => null
]);
}
}