codecamp

Laravel 项目开发规范 API 资源

用 API 资源

所有 API 返回的数据, 必须 使用 Laravel 自带的 API 资源 进行返回。

业务逻辑

绝不 在 API 资源中写业务逻辑。在 Service 层封装逻辑,输出数据,Resource 层只做定制。

所有读取逻辑,皆可封装到 Service 层或者 Model 层,不应该出现在 API Resources 层。

API Resources 层只负责确保返回数据格式。以及确保 API 返回结构的可溯性。

显性

API Resources 必须使用显性的数据结构,而非隐性。

❌ 隐性:

<?php

namespace App\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class AssetRateResource extends JsonResource
{
    public function toArray($request): array
    {
        return $this->resource->toArray();
    }
}

✅ 显性:

<?php

namespace App\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class AssetRateResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            // 把所需字段一个个列出来
            'asset_uuid' => $this->resource->asset_uuid,
            'rate'    => $this->resource->rate,
        ];
    }
}

返回数据格式

蛇形命名法 (snake case) 还是 驼峰命名法 (camel case)?

所有返回数据 必须 使用 蛇形命名法。接受请求的数据,也 必须 使用蛇形命名法。

❌ 驼峰:

{
    "userType": "robot",
    "avatarUrls": [
        "https://cdn.image.com/r9Z7phw4sFWwi-7YVqSiXuLo0wzMJk9asCrUFA=s256"
    ]
}

✅ 蛇形:

{
    "user_ype": "robot",
    "avatar_urls": [
        "https://cdn.image.com/r9Z7phw4sFWwi-7YVqSiXuLo0wzMJk9asCrUFA=s256"
    ]
}

参考 GitHub 的 API 设计:

前端如需使用驼峰命名,可使用 domchristie/humps 包对请求和结果的数据进行转换。


Laravel 项目开发规范 API 设计规范
Laravel 项目开发规范 权限和角色
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }