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. 灵活性、可维护性和类型安全性
相关推荐
分享点1 天前
Laravel 使用阿里云OSS S3 协议文件上传
阿里云·php·laravel
大熊不是猫2 天前
Laravel 事件与监听器
php·laravel·event
zh731418 天前
laravel在cli模式下输出格式漂亮一些
microsoft·php·laravel
wuzuyu36518 天前
Laravel The requested URL /hellowzy was not found on this server. 404 问题的解决
php·laravel
奔跑吧邓邓子20 天前
从0到1学PHP(十二):PHP 框架入门与项目实战
php·框架·laravel·项目实战·thinkphp·yii
hjc_04204323 天前
laravel下phpunit的使用
php·laravel
~央千澈~23 天前
05百融云策略引擎项目交付-laravel实战完整交付定义常量分文件配置-独立建立lib类处理-成功导出pdf-优雅草卓伊凡
android·laravel·软件开发·金融策略
JSON_L1 个月前
Laravel 分页方案整理
数据库·php·laravel
stand_forever1 个月前
laravel框架优化
php·laravel
Python涛哥1 个月前
PHP框架之Laravel框架教程:1. laravel搭建
开发语言·php·laravel