定制 devravik/extended-resources 二次开发

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

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

devravik/extended-resources

Composer 安装命令:

composer require devravik/extended-resources

包简介

Extended utilities for Laravel API resources, including flexible formatting and response enhancements.

README 文档

README

Latest Version on Packagist Total Downloads Tests PHP Version License

Extended Resources is a small but powerful extension around Laravel API resources that lets you:

  • Define multiple named formats for the same resource using PHP 8 attributes.
  • Apply on-the-fly modifications to the serialized data (array merges, closures, invokable objects).
  • Use convenience enhancements like only() and except() without building custom transformers.
  • Adjust the HTTP status code directly from the resource.

It is designed to feel native to Laravel while giving you more control over how resources are shaped and delivered.

Requirements

Dependency Version
PHP ^8.1 | ^8.2 | ^8.3 | ^8.4
Laravel ^10.0 | ^11.0 | ^12.0

Installation

Install via Composer:

composer require devravik/extended-resources

There is no configuration or service provider registration required; the package is auto-discovered by Laravel.

Core Concepts

1. Defining Formats with Attributes

Extend Devravik\ExtendedResources\ExtendedResource instead of Illuminate\Http\Resources\Json\JsonResource, and define one or more #[Format] methods:

<?php

use Devravik\ExtendedResources\ExtendedResource;
use Devravik\ExtendedResources\Formatting\Attributes\Format;

class ProductResource extends ExtendedResource
{
    #[Format]
    public function summary(): array
    {
        return [
            'sku'   => $this->resource->sku,
            'name'  => $this->resource->name,
            'price' => $this->resource->price,
        ];
    }
}

If a resource defines only a single #[Format] method, that format is considered the default.

Multiple Formats

use Devravik\ExtendedResources\ExtendedResource;
use Devravik\ExtendedResources\Formatting\Attributes\Format;

class ProductResource extends ExtendedResource
{
    #[Format]
    public function summary(): array
    {
        return [
            'sku'  => $this->resource->sku,
            'name' => $this->resource->name,
        ];
    }

    #[Format]
    public function pricing(): array
    {
        return [
            'sku'      => $this->resource->sku,
            'price'    => $this->resource->price,
            'currency' => $this->resource->currency,
        ];
    }
}

// Choose a specific format at runtime
ProductResource::make($product)->format('pricing');

The format name defaults to the method name (summary, pricing, etc.).

2. Default Formats with #[IsDefault]

If you have multiple formats and want one to be used when no explicit format is selected, mark it with #[IsDefault]:

use Devravik\ExtendedResources\ExtendedResource;
use Devravik\ExtendedResources\Formatting\Attributes\Format;
use Devravik\ExtendedResources\Formatting\Attributes\IsDefault;

class UserProfileResource extends ExtendedResource
{
    #[Format]
    public function compact(): array
    {
        return [
            'id'   => $this->resource->id,
            'name' => $this->resource->name,
        ];
    }

    #[IsDefault, Format]
    public function detailed(): array
    {
        return [
            'id'      => $this->resource->id,
            'name'    => $this->resource->name,
            'email'   => $this->resource->email,
            'joined'  => $this->resource->created_at,
        ];
    }
}

If no explicit call to format() is made, the detailed format is used.

3. Modifying Resource Output

Every extended resource exposes a modify() method that lets you transform the final array:

// Simple array merge
ProductResource::make($product)
    ->modify(['is_featured' => true]);

// Using a closure
ProductResource::make($product)
    ->modify(function (array $data) {
        $data['price_with_tax'] = $data['price'] * 1.2;

        return $data;
    });

// Using an invokable object
ProductResource::make($product)
    ->modify(new class {
        public function __invoke(array $data): array
        {
            $data['label'] = strtoupper($data['name']);

            return $data;
        }
    });

Multiple modifications can be chained; they are applied in order.

4. Enhancements: except() and only()

Two small enhancements ship with the package:

  • Except + AppliesExceptFilter trait for excluding keys.
  • Only + AppliesOnlyFilter trait for whitelisting keys.
use Devravik\ExtendedResources\Enhancements\Except;
use Devravik\ExtendedResources\Enhancements\Only;
use Devravik\ExtendedResources\Enhancements\Traits\AppliesExceptFilter;
use Devravik\ExtendedResources\Enhancements\Traits\AppliesOnlyFilter;
use Devravik\ExtendedResources\ExtendedResource;
use Devravik\ExtendedResources\Formatting\Attributes\Format;

class CustomerResource extends ExtendedResource
{
    use AppliesExceptFilter;
    use AppliesOnlyFilter;

    #[Format]
    public function base(): array
    {
        return [
            'id'         => $this->resource->id,
            'name'       => $this->resource->name,
            'email'      => $this->resource->email,
            'created_at' => $this->resource->created_at,
        ];
    }
}

// Drop email from the payload
CustomerResource::make($customer)->except('email');

// Keep only ID + name
CustomerResource::make($customer)->only('id', 'name');

// You can also apply the enhancements manually:
CustomerResource::make($customer)->modify(new Except(['email']));
CustomerResource::make($customer)->modify(new Only(['id', 'name']));

5. Collections

Extended Resources work with both explicit collections and anonymous collections.

use Devravik\ExtendedResources\ExtendedResource;

class OrderResource extends ExtendedResource
{
    // ...
}

// Anonymous collection
return OrderResource::collection($orders);

Under the hood this uses ExtendedResourceCollection and ExtendedAnonymousResourceCollection, which proxy modification methods like format(), only(), and except() down to each resource in the collection.

6. Response Status Codes

All resources and collections use the SetsResponseStatus trait, which adds a setResponseStatus() helper:

use Symfony\Component\HttpFoundation\Response;

return ProductResource::make($product)
    ->setResponseStatus(Response::HTTP_CREATED);

This leaves your controller methods clean while still letting you adjust the status code where the data is built.

API Overview

ExtendedResource

Key methods:

  • format(string $name): static – choose a named format.
  • modify(callable|array $modification): static – queue a modification.
  • setResponseStatus(?int $code): static – override the response status.

ExtendedResourceCollection

Behaves similarly to Laravel's ResourceCollection, but:

  • Ensures collects is an ExtendedResource subclass.
  • Proxies unknown method calls to the underlying resource class when appropriate (e.g. format(), only(), etc.).

Attributes

  • #[Format(?string $name = null)] – declare a format; optional explicit name.
  • #[IsDefault] – mark a format as the default when multiple formats exist.

Testing

The package ships with a full PHPUnit test suite. To run it:

composer test

For HTTP tests in your own application, you can continue to rely on Laravel's built‑in response assertions when controllers return extended resources.

Contributing

Contributions are welcome:

  1. Fork the repository and create a feature branch from main.
  2. Add tests for any new functionality or bug fixes.
  3. Run composer test to ensure the suite passes.
  4. Follow PSR-12 / Laravel Pint style guidelines.
  5. Open a pull request with a clear description of the change.

Bug reports should include your PHP and Laravel versions, the package version, minimal reproduction code, and any relevant stack traces.

Security

If you discover a security vulnerability, please do not open a public GitHub issue.

Instead, email dev.ravikgupta@gmail.com with the subject line:

[SECURITY] devravik/extended-resources <short description>

You will receive a response as soon as possible with next steps.

Maintainer

Ravi K Gupta

License

The MIT License (MIT). See the LICENSE file for details.

devravik/extended-resources 适用场景与选型建议

devravik/extended-resources 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 2, 最近一次更新时间为 2026 年 03 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 devravik/extended-resources 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 31
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-02