定制 pepperfm/api-responder-for-laravel 二次开发

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

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

pepperfm/api-responder-for-laravel

最新稳定版本:3.0.1

Composer 安装命令:

composer require pepperfm/api-responder-for-laravel

包简介

Easy api responder template using via DI

README 文档

README

Latest Version on Packagist Total Downloads GitHub Actions

logo

Standardized API JSON responses for Laravel

Tip

Full Package Description: Helpful advice for doing things better or more easily.

Installation

composer require pepperfm/api-responder-for-laravel

Usage

Inject via Laravel DI

use Pepperfm\ApiBaseResponder\Contracts\ResponseContract;

class UserController extends Controller
{
    public function __construct(public ResponseContract $json)
    {
    }
}

Direct API (config-based data key)

The simplest approach — data key and wrapping are resolved from config:

public function index(Request $request)
{
    $users = User::query()->whereIn('id', $request->input('ids'))->get();

    return $this->json->response($users->toArray());
}

public function store(StoreUserRequest $request)
{
    $user = User::create($request->validated());

    return $this->json->stored($user->toArray());
}

public function destroy(User $user)
{
    $user->delete();

    return $this->json->deleted();
}

Builder API (explicit control)

Use the fluent builder when you need per-response control over data keys or wrapping:

// Explicit data key
public function index()
{
    $users = User::all();

    return $this->json->withDataKey('users')->response($users->toArray());
}

// REST method convention (singular key for show/update, plural for index/etc.)
public function show(User $user)
{
    return $this->json->forMethod('show')->response($user->toArray());
}

// Disable wrapping (data spread into response root)
public function stats()
{
    return $this->json->build()->withoutWrapping()->response($stats);
}

PHP Attributes (declarative style)

Use #[ResponseDataKey] and #[WithoutWrapping] attributes with fromAction():

use Pepperfm\ApiBaseResponder\Attributes\ResponseDataKey;
use Pepperfm\ApiBaseResponder\Attributes\WithoutWrapping;

#[ResponseDataKey('user')]
public function show(User $user): JsonResponse
{
    return $this->json->fromAction()->response($user->toArray());
}

#[ResponseDataKey] // defaults to singular 'entity'
public function edit(User $user): JsonResponse
{
    return $this->json->fromAction()->response($user->toArray());
}

#[WithoutWrapping]
public function stats(): JsonResponse
{
    return $this->json->fromAction()->response($stats);
}

Pagination

public function index(Request $request)
{
    $users = User::query()->paginate();

    return $this->json->paginated($users);
}

// With data mapping
public function index(Request $request)
{
    $users = User::query()->paginate();
    $dtoCollection = $users->getCollection()->mapInto(UserDto::class);

    return $this->json->paginated($dtoCollection->toArray(), $users);
}

Error responses

return $this->json->error('Not found', 404);
return $this->json->error('Validation failed', 422, $validator->errors());

Facades

use Pepperfm\ApiBaseResponder\Facades\BaseResponse;

return BaseResponse::response($data);
return BaseResponse::forMethod('index')->response($data);
return BaseResponse::fromAction()->response($data);

Method injection / resolve

public function index(Request $request, ResponseContract $json)
{
    return $json->response($users->toArray());
}

// or
return resolve(ResponseContract::class)->response($users->toArray());

Paginated response format

The pagination meta is extracted automatically from LengthAwarePaginator or CursorPaginator:

export interface IPaginatedResponse<T> {
    current_page: number
    per_page: number
    last_page: number
    data: T[]
    from: number
    to: number
    total: number
    prev_page_url?: any
    next_page_url: string
    links: IPaginatedResponseLinks[]
}

export interface IPaginatedResponseLinks {
    url?: any
    label: string
    active: boolean
}

Configuration

Publish the config file:

php artisan vendor:publish --provider="Pepperfm\ApiBaseResponder\Providers\ApiBaseResponderServiceProvider" --tag="config"

Key options:

  • plural_data_key — data key for collections (default: 'entities')
  • singular_data_key — data key for single items (default: 'entity')
  • without_wrapping — disable data-key wrapping globally (default: false)
  • using_for_rest — enable REST method-based key resolution (default: true)
  • methods_for_singular_key — methods that use singular key (default: ['show', 'update'])
  • force_json_response_header — auto-add Accept: application/json to API requests (default: true)

Check the configuration file to customize response wrapping as you prefer

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email Damon3453@yandex.ru instead of using the issue tracker.

Credits

License

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

统计信息

  • 总下载量: 1.59k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 5
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-04-29

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固