Laravel Trait 实现 统一JSON 响应格式

什么是 Trait ?

Trait 是 PHP 5.4 引入的一个代码复用机制,它解决了 PHP 单继承的限制问题。

1.Trait 基本概念

Trait 是一种代码复用机制,即可以理解为 可重用的方法集合

php 复制代码
trait Loggable {
    public function log($message) {
        echo "Log: $message\n";
    }
}

2.Trait 的特点

  • 不是类:不能实例化

  • 不是接口:可以包含具体实现

  • 解决单继承限制:一个类可以使用多个 Trait,这是重点,因为PHP只能单继承,很好弥补了这一弱势。

  • 代码复用:可以理解为帮助方法,多个类使用,不用重复多次写

3.Trait的 使用 ,Use 即可

php 复制代码
class User {
    use Loggable ;
}

//laravel 常见的伪删除,等等
class User extends Model {
    use SoftDeletes; // 软删除功能
}

4.多个 Trait 使用

php 复制代码
class MyClass {
    use TraitA, TraitB;
}

5.当多个 Trait 有同名方法时

php 复制代码
trait A {
    public function conflict() { echo "A"; }
}
trait B {
    public function conflict() { echo "B"; }
}
class MyClass {
    use A, B {
        A::conflict insteadof B;  // 使用 A 的 conflict 方法
        B::conflict as conflictB; // 将 B 的 conflict 方法重命名
    }
}

6.Trait 与继承的优先级

方法解析优先级(从高到低):

  1. 当前类中的方法权重最高

  2. 其次是Trait 中的方法

  3. 最后继承的父类中的方法

Trait 还有一些其他的特性 等等,大家去看看语法。重点来了

统一JSON 响应类开放。

直接上源码:

php 复制代码
<?php
namespace App\Http\Trait;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Response;

trait ResponseJson
{
    /**
     * 默认成功状态码
     */
    protected int $successCode = 200;

    /**
     * 默认错误状态码
     */
    protected int $errorCode = 101;

    /**
     * 返回成功 JSON 响应
     *
     * @param string $message 成功消息
     * @param mixed $data 返回数据
     * @param array $headers 附加头信息
     * @param int $httpStatus HTTP 状态码
     * @return JsonResponse
     */
    public function success(
        string $message,
        mixed  $data = [],
        array  $headers = [],
        int    $httpStatus = 200
    ): JsonResponse
    {
        return Response::json([
            'code' => $this->successCode,
            'message' => $message,
            'data' => $data,
        ], $httpStatus, $headers);
    }

    /**
     * 返回错误 JSON 响应
     *
     * @param string $message 错误消息
     * @param int|null $code 业务错误码
     * @param mixed $data 附加数据
     * @param array $headers 附加头信息
     * @param int $httpStatus HTTP 状态码
     * @return JsonResponse
     */
    public function error(
        string $message,
        int    $code = NULL,
        mixed  $data = [],
        array  $headers = [],
        int    $httpStatus = 400
    ): JsonResponse
    {
        return Response::json([
            'code' => $code ?? $this->errorCode,
            'message' => $message,
            'data' => $data,
        ], $httpStatus, $headers);
    }

    /**
     * 根据数据自动返回成功或错误响应
     *
     * @param array $responseData 必须包含 code, message, data
     * @param array $headers 附加头信息
     * @return JsonResponse
     */
    public function autoResponse(array $responseData, array $headers = []): JsonResponse
    {
        if(!isset($responseData['code'], $responseData['message'])){
            return $this->error('Invalid response format', 500, [], $headers, 500);
        }

        return $responseData['code'] === $this->successCode
            ? $this->success($responseData['message'], $responseData['data'] ?? [], $headers)
            : $this->error($responseData['message'], $responseData['code'], $responseData['data'] ?? [], $headers);
    }
}

1. Api接口直接使用

php 复制代码
class TestController extends Controller
{
    use ResponseJson;

    public function index()
    {
        //return $this->success('success', [1, 2, 3]);
        return $this->error('error', 11, [1, 2, 3]);
    }
}

2.代码分析

  1. 封装了成功和错误和自定义的响应方法,success ,error,autoResponse
  2. 支持自定义 HTTP 状态码和 headers
  3. success ,error 保持一致的参数顺序 (消息 -> 数据/代码 -> headers -> HTTP状态码),使用的时候尽量减少干扰
  4. 区分业务编码 code 和 HTTP 状态码 httpStatus,一个是业务上的区分,一个是接口通信上的状态。
  5. 增强的 autoResponse 方法,处理自定义的相关情况
  6. 严格的参数类型声明和验证
  7. 灵活性、可维护性和类型安全性
相关推荐
景天科技苑4 天前
【Rust trait特质】如何在Rust中使用trait特质,全面解析与应用实战
开发语言·后端·rust·trait·rust trait·rust特质
bubiyoushang8887 天前
深入探索Laravel框架中的Blade模板引擎
android·android studio·laravel
tianlebest8 天前
Laravel 安全:批量赋值 fillable 与 guarded
数据库·安全·laravel
深山技术宅9 天前
在Laravel 12中实现基于parent_id的树状数组
php·laravel
深山技术宅12 天前
在 Laravel 12 中实现 WebSocket 通信
websocket·php·laravel
深山技术宅12 天前
laravel 12 监听syslog消息,并将消息格式化后存入mongodb
mongodb·php·laravel
深山技术宅16 天前
Laravel 12 实现 API 登录令牌认证
php·laravel
深山技术宅16 天前
Laravel 12 实现 OAuth2 登录
php·laravel
Taichi呀16 天前
Laravel+API 接口
php·laravel
Taichi呀18 天前
Laravel基础
php·laravel