franco2911 / avrestirouter
一个快速简单的PHP路由器
1.0.0
2024-06-21 16:14 UTC
Requires
- php: ^8.3
- guzzlehttp/guzzle: ^7.8
Requires (Dev)
- filp/whoops: ^2.7
- phpunit/phpunit: ^11.2
- symfony/var-dumper: ^5.1
This package is auto-updated.
Last update: 2024-09-24 13:20:19 UTC
README
AvrestiRouter 是一个由 Laravel 启发、简单而强大的 PHP 路由库。它提供了一组易于使用的 API,用于定义和解析路由、处理不同的 HTTP 方法以及管理带有命名参数的路由组。
功能
- 支持所有 HTTP 方法(GET、POST、PUT、PATCH、DELETE)
- 命名路由参数,支持动态路由
- 分组路由,提高组织效率
- 自定义正则表达式模式的路由参数
要求
- PHP >= 8.3
安装
您可以使用 Composer 安装 AvrestiRouter
composer require franco2911/avrestirouter
入门指南
初始化 AvrestiRouter
首先,初始化 AvrestiRouter
并使用 Route
门面设置它
require 'vendor/autoload.php'; use AvrestiRouter\Routing\AvrestiRouter; use AvrestiRouter\Routing\Facade\Route; $router = new AvrestiRouter(); Route::setRouter($router);
定义路由
您可以使用 Route
门面来定义路由。以下是一些不同路由定义的示例
基本路由
Route::get('/contact', function () { return new \GuzzleHttp\Psr7\Response(200, [], "<h1>Contact page</h1>"); });
命名路由
Route::get('/about', function () { return new \GuzzleHttp\Psr7\Response(200, [], "<h1>About page</h1>"); })->name('about');
分组路由
Route::group(['group' => 'auth'], function () { Route::get('/dashboard', function () { return new \GuzzleHttp\Psr7\Response(200, [], "Dashboard"); })->name('dashboard'); Route::get('/settings', [\TestController::class, 'create'])->name('settings'); Route::get('/profile/{id}', function ($id) { return new \GuzzleHttp\Psr7\Response(200, [], "<h1>Profile ID: $id</h1>"); })->name('profile.show'); });
解析路由
要基于传入的请求解析当前路由,请使用 resolve
方法。您可以使用 Guzzle 创建一个 ServerRequest
实例
use GuzzleHttp\Psr7\ServerRequest; $request = ServerRequest::fromGlobals(); $response = Route::resolve($request); // Output the response body echo $response->getBody();
从路由名称生成 URL
您可以使用 generateUrl
方法为命名路由生成 URL
echo Route::generateUrl('profile.show', ['id' => 1259]); // Output: /profile/1259
示例用法
您可以在示例目录中找到一个完整的示例,演示了 AvrestiRouter 的使用。
许可证
本项目采用 MIT 许可证。有关详细信息,请参阅 LICENSE 文件。
贡献
欢迎贡献!请复制此存储库并提交拉取请求以贡献改进或新功能。