筆記:統一的介面響應類 HttpService

Diego_crazy發表於2021-09-04

對API響應做統一的封裝,讓程式碼看起來更清晰一些。
HttpService 主要提供3個方法:success, error, validate
success和error方法統一響應相同格式的資料結構:
{“msg”: “測試錯誤”,”data”: [],”code”: 0}
validate方法只是基於系統Validator的封裝。

程式碼:

<?php


namespace App\Service;


use Illuminate\Support\Facades\Validator;

class HttpService
{
    public function __construct()
    {

    }

    /**
     * success
     * @param $message
     * @param array $content
     * @param int $code
     * @param int $status
     * @return \Illuminate\Http\JsonResponse
     */
    public static function success($message, $content = [], $code = 1, $status = 200)
    {
        if (empty($content)) {
            $data['msg'] = 'success, but data is empty!';
            $data['code'] = $code;
        } else {
            $data['msg'] = $message;
            $data['data'] = $content;
            $data['code'] = $code;
        }

        return response()->json($data, $status);
    }

    /**
     * error
     * @param $message
     * @param array $content
     * @param int $code
     * @param int $status
     * @return \Illuminate\Http\JsonResponse
     */
    public static function error($message, $content = [], $code = 0, $status = 200)
    {
        if (empty($content)) {
            $data['msg'] = $message;
            $data['code'] = $code;
        } else {
            $data['msg'] = $message;
            $data['data'] = $content;
            $data['code'] = $code;
        }

        return response()->json($data, $status);
    }

    /**
     * 欄位校驗
     * @param $all
     * @param $rule
     * @param array $message
     * @param array $attribute
     * @return bool|string
     */
    public static function validate($all, $rule, $message = [], $attribute = [])
    {
        if (empty($message)) {
            $message = self::getMessage();
        }
        if (empty($attribute)) {
            $attribute = self::getAttributes();
        }
        $validate = Validator::make($all, $rule, $message, $attribute);
        if ($validate->fails()) {
            return implode(' ', $validate->errors()->all());
        }

        return false;
    }

    /**
     * 欄位校驗規則轉義(愛寫不寫)
     *      預設: resource/lang/en/validation.php
     * @return array
     */
    public static function getMessage()
    {
        return [
            'required' => '欄位 :attribute 是必須的.',
            'unique' => '欄位 :attribute 資料已經存在.',
            'between' => '欄位 :attribute 必須在 :min - :max.之間',
        ];
    }

    /**
     * 欄位校驗欄位轉義(愛寫不寫)
     *      預設: resource/lang/en/validation.php (attributes)
     * @return array
     */
    public static function getAttributes()
    {
        return [];
    }


}

然後來簡單對比一下:
官方手冊demo寫法:

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return $validator->errors();
        }

        // response json
        return response()->json();
    }

基於HttpService類:

    public function storeNew(Request $request)
    {
        if ($error = HttpService::validate($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ])) {
            return $error;
        }

        return HttpService::success('ok');
    }

個人覺得好像更簡單優雅了一些,實際也沒啥區別。
小結:非喜勿擾,全憑喜好:laughing:

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章