devravik/extended-resources
Composer 安装命令:
composer require devravik/extended-resources
包简介
Extended utilities for Laravel API resources, including flexible formatting and response enhancements.
关键字:
README 文档
README
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()andexcept()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+AppliesExceptFiltertrait for excluding keys.Only+AppliesOnlyFiltertrait 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
collectsis anExtendedResourcesubclass. - 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:
- Fork the repository and create a feature branch from
main. - Add tests for any new functionality or bug fixes.
- Run
composer testto ensure the suite passes. - Follow PSR-12 / Laravel Pint style guidelines.
- 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
- Website: devravik.github.io
- Email:
dev.ravikgupta@gmail.com - LinkedIn: linkedin.com/in/ravi-k-dev
- GitHub: github.com/devravik
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 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 devravik/extended-resources 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Serializer transformers outputting valid API responses in JSON, JSON API and HAL+JSON API formats.
Symfony 2 & 3 JSON API Transformer Package
A simple library that allows transform any kind of data to native php data or whatever
HAL+JSON & HAL+XML API transformer outputting valid API responses.
HTTP request logger middleware for Laravel
Optimus Bard takes the content from a Statamic Bard field and transforms it into a string when updating your search index
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 31
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-02