定制 creativecrafts/laravel-api-response 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

creativecrafts/laravel-api-response

Composer 安装命令:

composer require creativecrafts/laravel-api-response

包简介

Laravel API Response is a powerful and flexible package that provides a standardized way to structure API responses in Laravel applications. It offers a range of features to enhance your API development experience, including consistent response formatting, conditional responses, pagination support,

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Code Coverage Total Downloads

Laravel API Response is a powerful and flexible package that provides a standardized way to structure API responses in Laravel applications. It offers a range of features to enhance your API development experience, including consistent response formatting, conditional responses, pagination support, rate limiting, and more.

Table of Contents

1. [Installation](#installation)
2. [Configuration](#configuration)
3. [Basic Usage](#basic-usage)
4. [Feature](#feature)
    - [Success Response](#success-response)
    - [Error Response](#error-response)
    - [Conditional Response](#conditional-response)
    - [Pagination](#pagination)
    - [Rate Limiting](#rate-limiting)
    - [Response Compression](#response-compression)
    - [Localization](#localization)
    - [HATEOAS Links](#hateoas-links)
    - [Logging](#logging)
5. [Advanced Usage](#advanced-usage)
6. [Testing](#testing)
7. [Changelog](#changelog)
8. [Contributing](#contributing)
9. [Security Vulnerabilities](#security-vulnerabilities)
10. [Credits](#credits)
11. [License](#license)

1. Installation

You can install the package via composer:

composer require creativecrafts/laravel-api-response

2. Configuration

The package comes with a default configuration file that you can publish to your application using the following command:

php artisan vendor:publish --tag=api-response-config

This will create a laravel-api-response.php file in your config directory. You can customize various aspects of the package behavior in this file.

3. Basic Usage

There are two ways to use the Laravel API Response in your controllers:

Using Dependency Injection

You can inject the LaravelApi class:

use CreativeCrafts\LaravelApiResponse\LaravelApi;

class UserController extends Controller
{
    protected $api;

    public function __construct(LaravelApi $api)
    {
        $this->api = $api;
    }

    public function index()
    {
        $users = User::all();
        return $this->api->successResponse('Users retrieved successfully', $users);
    }
}

Using the Facade

For a more Laravel-like experience, you can use the LaravelApiResponse facade:

use CreativeCrafts\LaravelApiResponse\Facades\LaravelApiResponse;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return LaravelApiResponse::successResponse('Users retrieved successfully', $users);
    }
}

4. Feature

The Laravel API Response package provides a range of features to help you build robust and reliable APIs. Here are some of the key features:

Success Responses

To return a success response:

return $this->api->successResponse('Operation successful', $data);

Error Responses

To return an error response:

return $this->api->errorResponse('An error occurred', $errorCode, $statusCode);

Conditional Responses

For responses that support caching and conditional requests:

return $this->api->conditionalResponse($data, 'Data retrieved successfully');

This method automatically handles ETag and Last-Modified headers for efficient caching.

Pagination

The package supports Laravel's pagination:

$users = User::paginate(15);
return $this->api->paginatedResponse('Users retrieved successfully', $users);

Rate Limiting

Rate limiting is automatically applied to API routes. You can configure the rate limit in the laravel-api-response.php config file:

'rate_limit_max_attempts' => env('API_RATE_LIMIT_MAX_ATTEMPTS', 60),
'rate_limit_decay_minutes' => env('API_RATE_LIMIT_DECAY_MINUTES', 1),

Response Compression

Response compression can be enabled or disabled in the config:

'enable_compression' => env('API_RESPONSE_COMPRESSION', true),

Localization

The package supports message localization. Use the localize method to translate messages:

$message = $this->api->localize('messages.welcome');

HATEOAS Links

You can include HATEOAS links in your responses:

$links = [
    'self' => ['href' => '/api/users/1'],
    'posts' => ['href' => '/api/users/1/posts'],
];

return $this->api->successResponse('User retrieved', $userData, 200, [], $links);

Logging

API responses are logged to a dedicated channel. You can configure the channel in the config file:

'log_channel' => 'api',

Exception Handling

The package includes a custom exception handler that automatically formats exceptions into consistent API responses. This is enabled by default and can be configured in the config file:

'use_exception_handler' => env('API_USE_EXCEPTION_HANDLER', true),

When enabled, the exception handler will automatically catch exceptions and format them into API responses with appropriate status codes. For example:

  • Validation exceptions will be formatted as validation error responses
  • Model not found exceptions will be formatted as 404 error responses
  • Authentication exceptions will be formatted as 401 error responses
  • Authorization exceptions will be formatted as 403 error responses

This ensures consistent error responses across your API without requiring extra code in your controllers.

5. Advanced Usage

The Laravel API Response package provides a range of advanced features to help you build robust and reliable APIs. Here are some of the key features:

Custom Response Structure

You can customize the response structure in the config file:

'response_structure' => [
    'success_key' => 'success',
    'message_key' => 'message',
    'data_key' => 'data',
    'errors_key' => 'errors',
    'error_code_key' => 'error_code',
    'meta_key' => 'meta',
    'links_key' => '_links',
    'include_api_version' => true,
],

Filtering Response Fields

You can filter the fields returned in the response:

$fields = ['id', 'name', 'email'];
return $this->api->successResponse('User data', $userData, 200, [], [], $fields);

Custom Status Codes

You can specify custom HTTP status codes for your responses:

return $this->api->successResponse('Resource created', $newResource, 201);

Extending with Custom Methods

The LaravelApi class uses Laravel's Macroable trait, allowing you to add custom response methods at runtime:

use CreativeCrafts\LaravelApiResponse\LaravelApi;
use Illuminate\Support\Facades\Response;

LaravelApi::macro('teapotResponse', function ($message = "I'm a teapot") {
    return Response::json(['message' => $message], 418);
});

// Then in your controller:
return $this->api->teapotResponse();
// Or using the facade:
return LaravelApiResponse::teapotResponse("Custom teapot message");

This makes it easy to extend the package with your own custom response types without modifying the core code.

Version 2: Breaking Changes

Version 2 of the package introduces one breaking change.

  • createdResponse method has been removed. Use successResponse instead.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

creativecrafts/laravel-api-response 适用场景与选型建议

creativecrafts/laravel-api-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.45k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 12 月 07 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「laravel-api-response」 「creativeCrafts」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 creativecrafts/laravel-api-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 creativecrafts/laravel-api-response 我们能提供哪些服务?
定制开发 / 二次开发

基于 creativecrafts/laravel-api-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.45k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 11
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-12-07