artkoder / peasy-router
一个简单、易于使用且具有偏见的PHP路由器
v0.1.1
2023-09-24 10:41 UTC
Requires
- php: >=7.4
- artkoder/kvpparser: ^0.1.0
Requires (Dev)
- phpunit/phpunit: ^10.3
README
Peasy Router是一个简单且具有偏见的PHP路由器。它旨在用于需要非常基本的路由功能的小型项目。没有任何复杂的事情。
安装
使用composer
composer require artkoder/peasy-router
配置你的 .htaccess 文件
将以下代码添加到与你的 index.php
同级别的public文件夹中的 .htaccess
文件内。
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
设置 index.php
// public/index.php require_once __DIR__ . '/../vendor/autoload.php'; use ArtKoder\Peasy\Http\Router; // You need to pass the path to your routes directory $router = new Router('/path/to/routes/directory'); $router->handleRequest();
路由
你可以在一个目录中定义你的路由。你可以使用扩展名为 .routes
的文本文件或普通的 .php
文件。Peasy路由器会递归地扫描目录内的所有路由文件。你可以使用这两种文件格式中的任何一种,或者根据需要组合两者。
使用 .routes
文件定义你的路由
以下是一个示例 web.routes
文件
name: budget-report path: /budget/{start}/{end} method: get controller: ArtKoder\Peasy\Controllers\Budget::report name: budget-index path: /budget method: get controller: ArtKoder\Peasy\Controllers\Budget::index
使用 .php
文件定义你的路由
前面的路由可以如下在 .php
文件中定义
// web.php return [ [ 'name' => 'budget-report', 'path' => '/budget/{start}/{end}', 'method' => 'get', 'controller' => 'ArtKoder\Peasy\Controllers\Budget::report' ], [ 'name' => 'budget-index', 'path' => '/budget', 'method' => 'get', 'controller' => 'ArtKoder\Peasy\Controllers\Budget::index' ] ];
控制器
一旦你有了路由定义,你可以为你的路径创建控制器。
以下是一个使用前面路由定义的示例
// src/Controllers/Budget.php namespace ArtKoder\Peasy\Controllers; class Budget { public static function report($start, $end) { echo "start: $start\n"; echo "end: $end\n"; } public static function index() { echo "Budget index\n"; } }
查询参数
Peasy路由器将所有查询参数映射为控制器函数的参数。因此,如果你请求以下路径: https://peasy.test/budget/2023-09-01/2023-12-31?var=value
,控制器将期望获取一个变量 $var
,因此你需要声明它。为了避免查询参数不存在时的错误,你可以使变量为可选。
以下是一个示例
// src/Controllers/Budget.php namespace ArtKoder\Peasy\Controllers; class Budget { public static function report($start, $end, $var = '') { echo "start: $start\n"; echo "end: $end\n"; echo "var: $var\n"; } public static function index() { echo "Budget index\n"; } }