mrldavies/wp-rest-fluent
Composer 安装命令:
composer require mrldavies/wp-rest-fluent
包简介
A fluent routing layer for the WordPress REST API with middleware, groups and response formatting.
README 文档
README
A fluent routing layer for the WordPress REST API with middleware, groups and response formatting.
Inspired by Laravel-style routing and middleware patterns, adapted for WordPress.
Requirements
- PHP >= 8.1
- WordPress (must run inside a WP environment)
If using Roots Sage, v10 or above is required.
Installation
Install via Composer:
composer require mrldavies/wp-rest-fluent
Basic Usage
Import the class:
use Mrldavies\WpRestFluent\Rest;
Define your routes:
Rest::get('/hello/{name:alpha}') ->handler(function ($request) { return [ 'data' => ['message' => "Hello {$request['name']}"], 'status' => 200, ]; }) ->formatter();
Register routes during boot:
add_action('plugins_loaded', function () { Rest::registerRoutes(); });
Using with Roots Sage (v10+)
If using Roots Sage v10 or above (Acorn-based), register routes inside a service provider.
Example:
<?php namespace App\Providers; use Roots\Acorn\Sage\SageServiceProvider; use Mrldavies\WpRestFluent\Rest; class ThemeServiceProvider extends SageServiceProvider { public function register() { Rest::registerRoutes(); parent::register(); } public function boot() { parent::boot(); } }
Ensure your provider is registered in config/app.php.
This works because Acorn bootstraps WordPress hooks correctly within the container lifecycle.
HTTP Methods
Rest::get('/endpoint') Rest::post('/endpoint') Rest::put('/endpoint') Rest::patch('/endpoint') Rest::delete('/endpoint')
Route Parameters
You can define typed parameters using curly braces:
Rest::get('/product/{id:int}') Rest::get('/user/{name:alpha}') Rest::get('/optional/{slug?}')
Supported built-in types
int→[0-9]+alpha→[a-zA-Z]+- default (no type) →
[a-zA-Z0-9-+_]+
Example:
Rest::get('/invoice/{ref}')
Optional parameter:
Rest::get('/category/{slug?}')
Advanced / Raw Regex Routes
If you require full regex control, you can bypass the curly-brace syntax entirely and use native WordPress-style patterns:
Rest::get('/legacy/age(?:/(?P<id>[0-9]+))')
This gives complete control over route matching.
Response Handling
Your handler may return:
Array
return [ 'data' => $payload, 'status' => 200, ];
Object
return (object)[ 'data' => $payload, 'status' => 200, ];
Returning WP Native Responses
You may also return:
WP_REST_ResponseWP_Error
These will be passed through untouched.
Formatter
Enable formatted responses:
->formatter();
Output shape:
{
"data": {...},
"status": 200,
"success": true
}
Mapping Custom Response Shapes
If your handler returns a different structure:
return [ 'payload' => [...], 'code' => 418 ];
Map it:
Rest::get('/example') ->map('payload', 'code') ->handler(fn() => externalCall()) ->formatter();
Middleware
Attach middleware to routes:
use Mrldavies\WpRestFluent\Middleware\RateLimitMiddleware; Rest::get('/limited') ->middleware([new RateLimitMiddleware(3, 1)]) ->handler(fn() => ['data' => ['ok' => true], 'status' => 200]) ->formatter();
Middleware follows the same conceptual structure as Laravel middleware.
Laravel middleware documentation: https://laravel.com/docs/middleware
Your middleware must implement:
public function handle($request, $next)
To continue the chain:
return $next($request);
Middleware may return:
WP_REST_ResponseWP_Error- Or allow execution to continue
Middleware execution order is LIFO (last attached runs closest to the handler).
Shipped Middleware
RateLimitMiddleware
The package includes a simple transient-based rate limiter.
Example:
Rest::get('/limited') ->middleware([new RateLimitMiddleware(5, 1)]) // 5 requests per 1 minute ->handler(...) ->formatter();
Features:
- Per-IP limiting
- Per-user limiting when logged in
- Sliding window
- Returns HTTP 429 with
Retry-Afterheader
The rate limiter is provided as a convenience and can be replaced or extended.
Route Groups
Group routes under shared configuration:
Rest::group(['prefix' => 'v2'], function () { Rest::get('/users') ->handler(fn() => ['data' => [], 'status' => 200]) ->formatter(); });
You may also group middleware and permissions:
Rest::group([ 'prefix' => 'admin', 'middleware' => [new RateLimitMiddleware(10, 1)], ], function () { Rest::get('/dashboard') ->permissions(fn() => current_user_can('manage_options')) ->handler(...) ->formatter(); });
Permissions
Attach permission callbacks:
Rest::get('/admin') ->permissions(function () { return current_user_can('manage_options'); }) ->handler(fn() => ['data' => ['ok' => true], 'status' => 200]) ->formatter();
Permission callbacks must return:
truefalse- or
WP_Error
Custom Namespace Prefix
Default namespace prefix is v1.
Override per-route:
Rest::get('/custom') ->prefix('v9') ->handler(...)
Debugging Routes
Inspect registered routes:
Rest::debugRoutes();
Notes
- Designed specifically for WordPress REST API.
- Requires WordPress runtime.
- Middleware architecture mirrors Laravel's pipeline concept.
- Supports array and object response normalization.
- Allows full custom WordPress regex routes when needed.
License
MIT
mrldavies/wp-rest-fluent 适用场景与选型建议
mrldavies/wp-rest-fluent 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 232 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 02 月 28 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「fluent」 「wordpress」 「router」 「middleware」 「rest-api」 「wp-rest」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 mrldavies/wp-rest-fluent 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 mrldavies/wp-rest-fluent 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 mrldavies/wp-rest-fluent 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Presentation and Formatting helper with nice fluent interface.
Traits gathering fluent syntax common methods
A modern, fluent HTTP client. Forked from Mashape, reimagined by Nidux, and open-sourced for the PHP community.
A fluent PHP CURL wrapper
Router
Laravel-first Zabbix JSON-RPC API client with fluent, testable DX.
统计信息
- 总下载量: 232
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 25
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-02-28