nycu-csit/laravel-restful-utils
Composer 安装命令:
composer require nycu-csit/laravel-restful-utils
包简介
Restful API utilities for Laravel projects
关键字:
README 文档
README
This package provides utilities for building a restful API for Laravel projects.
This package requires PHP >= 8.0, and supports Laravel 9~13.
Setup
In order to enable error wrapping feature, you should update your app/Exceptions/Handler.php.
Make Handler extends NycuCsit\LaravelRestfulUtils\Exceptions\Handler instead of original one.
And we suggest you add HttpApiException into the $dontReport list:
use NycuCsit\LaravelRestfulUtils\Exceptions\HttpApiException; protected $dontReport = [ HttpApiException::class, ];
Exceptions
We suggest throwing exceptions instead of returning a response to indicate the status.
These exceptions help you to give a well-wrapped error response:
- NycuCsit\LaravelRestfulUtils\Exceptions\HttpApiException
- NycuCsit\LaravelRestfulUtils\Exceptions\ForbiddenException
Error Wrapping
When enabled, error responses are represented like this:
{
"error": {
"code": "CONFLICT_STATUS",
"message": "You cannot update this resource because it was locked."
}
}
The code should be a string to simply indicate the type of error. The client may use it as error identifier.
The message should be a human-readable string to show the reason or what happened. You may provide localized message.
API Controller
This package provides controllers for you to reduce many duplicated logics. Publish these controllers' base classes to your app/Http/Controller:
php artisan vendor:publish --tag=restful-controllers
Now, you can use ApiResourceController and ApiNestedResourceController in app/Http/Controller in your application.
These controllers are designed to integrate with Laravel's built-in features:
- resource controller for routing and actions
- form request for validation
- policy for authorization
- api resource for wrapping your data
So, we suggested you create a resource controller like this:
php artisan make:restful-controller UserController --model=User --requests
or for nested resource:
php artisan make:restful-controller PhotoController --model=Photo --parent=User --requests
Now, you may implement method stubs in your controller.
There are some properties can help you reduce passing arguments:
$this->requestthe request object$this->querythe query builder$this->modelthe model from route model binding$this->resultthe response or resource will be returned$this->parentModelthe parent model from route model binding, only for nested controllers
These properties are defined in Context trait.
Be careful!
Because of the route implicit binding, the action methods
(show(), store(), update(), destroy(), index() if nested resource is used) from the API Controllers cannot get
bindings, so you need write these action methods and call the parent version:
class PhotoController extends ApiResourceController { public function index(Request $request) { parent::indexAction($request); } public function store(StorePhotoRequest $request) { parent::storeAction($request); } public function show(Request $request, Photo $photo) { parent::showAction($request, $photo); } public function update(UpdatePhotoRequest $request, Photo $photo) { parent::updateAction($request, $photo); } public function destroy(Request $request, Photo $photo) { parent::destroyAction($request, $photo) } // ...
If you use the make:restful-controller command, these methods are generated for you.
There are many methods in the box, you can find each action method in Concerns folder, extend and override these methods to build something great!
Nested resource:
API Resource
For action method index() returns a collection of resources, action methods show(), store(), update() returns a single resource.
You may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users.
So, these methods may return API Resources instead of the model.
Class HasResourceActions and HasNestedResourceActions provides
function constructJsonResource() and constructResourceCollection() to construct resource instance that just wraps the model.
To use your own resource class, you may use the make:resource artisan command:
php artisan make:resource PhotoResource
and override these methods in your controller:
use App\Http\Resources\PhotoResource; class PhotoController extends ApiResourceController { // ... public function constructJsonResource($resource): JsonResource { return new PhotoResource($resource); } public function constructResourceCollection($resource): ResourceCollection { return new PhotoResource::collection($resource); } }
In most case, simply create a PhotoResource and use its ::collection() method to construct a resource collection.
In addition to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models.
To use your own collection class, you may use the artisan command to generate a collection:
php artisan make:resource User --collection
and override these methods in your controller:
use App\Http\Resources\PhotoResource; use App\Http\Resources\PhotoCollection; class PhotoController extends ApiResourceController { // ... public function constructJsonResource($resource): JsonResource { return new PhotoResource($resource); } public function constructResourceCollection($resource): ResourceCollection { return new PhotoCollection($resource); } }
Pagination
See: Pagination
You can add these properties in the controller to override the default value for pagination:
protected bool $alwaysPaginate = true; protected bool $enablePaginate = true; protected int $defaultLimit = 20; protected int $maxLimit = 100;
When the pagination enabled, query params page and limit may be used in the URL.
Datetime store in local timezone
Laravel just stores the date in the model by the original hour/time of the date but without preserving the timezone
information. You may use the custom cast LocalDatetime to transform date to local
timezone (config('app.timezone')) date for setting model attribute.
Attach LocalDatetime to a model attribute:
// import it use NycuCsit\LaravelRestfulUtils\Casts\LocalDatetime; // Attach it in the model class protected $casts = [ 'my_column' => LocalDatetime::class, ];
Once you attached LocalDatetime, you may assign an ISO 8601 string or a Carbon instance to my_column attribute.
If you need immutable instance or a date only (without time) attribute, here are parameters for you:
protected $casts = [ 'my_column1' => LocalDatetime::class . LocalDatetime::DATE_ONLY, 'my_column2' => LocalDatetime::class . LocalDatetime::IMMUTABLE, 'my_column3' => LocalDatetime::class . LocalDatetime::DATE_ONLY_IMMUTABLE, ];
nycu-csit/laravel-restful-utils 适用场景与选型建议
nycu-csit/laravel-restful-utils 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 719 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 09 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 nycu-csit/laravel-restful-utils 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 nycu-csit/laravel-restful-utils 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 nycu-csit/laravel-restful-utils 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Alfabank REST API integration
Laravel package for Accurate Online API integration.
Shared RCX Laravel DataTables UI and configuration helpers.
Boot a Laravel project on any machine with one command: app:serve installs missing tools (PHP, Node, Composer, Herd, Docker), creates .env, sets up the database, runs migrations, builds assets, starts a queue worker and serves via Herd, Sail or artisan serve; app:down cleanly stops everything it sta
Branded, diagnostic error pages (500, 403, 404, 419, 503) for Filament — native Filament UI, dark mode and translations out of the box.
Turn any PDF into a Pingen-ready A4 letter (generated address cover page + A4 normalisation + safe margins) and send it through the Pingen print & mail API. Laravel-first.
统计信息
- 总下载量: 719
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 4
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-09-19