grogorick/php-routing
Composer 安装命令:
composer require grogorick/php-routing
包简介
Minimal PHP routing with zero dependencies
README 文档
README
Set callbacks for hierarchical routes in a simple associative array structure.
Setup
composer require grogorick/php-routing
Example
# api.php require_once 'vendor/autoload.php'; use Grogorick\PhpRouting as R; ... function get_feed($GET_data) { $feed_data = ... if ($feed_data) R\respond($feed_data); else R\respond(null, R\Response::ERROR_NOT_FOUND); } ... R\route([ 'v1' => [ 'sign-in' => [ 'POST' => 'App\Auth\sign_in' ], '(authenticated)' => R\Check('App\Auth\verify_authorization_header', [ 'accounts' => R\Entity([ 'POST' => fn() => R\respond('create account'), 'GET' => fn() => R\respond('list accounts'), '/\w+/' => fn($account_slug) => R\Item([ 'GET' => fn() => R\respond('get account ' . $account_slug), 'PUT' => fn() => R\respond('replace account ' . $account_slug), 'PATCH' => fn() => R\respond('update account ' . $account_slug), 'DELETE' => fn() => R\respond('delete account ' . $account_slug) ]), ... ]), 'posts' => R\Entity([ /* post_id */ '/\d+/' => R\IntParam([ 'GET' => fn($post_id) => R\respond('get post ' . $post_id), ... ]), ... ]), 'feed' => [ 'GET' => fn($GET_data) => get_feed($GET_data), ... ], ... ]), ... ], ... ]);
Routes Array Syntax
route-literal => [subroutes array]
static route literal string => subroutes array
/regex/ => subroutes function
regex to match a URL parameter => subroutes function getting the parsed parameter, generating a subroutes array
(subroutes group) => subroutes function
subroutes group name in parentheses => subroutes function generating a subroutes array
METHOD => callable
request METHOD in full uppercase => action callable to be called for this route
Action callables will be called with the following arguments:
URL parameters — in their order withing the respective route
form data — via$_POSTorfile_get_contents('php://input')
search parameters — via$_GET
Reference
route($routes)
Main function to parse the current request URL and call the corresponding callback function.
$routes (associative array)
— route literal string => subroute array
— route parameter regex => closure with parsed parameter as argument, returning a subroute array
— request method (POST/GET/PUT/PATCH/DELETE) => callback function
respond($response, $code = 200)
Helper function to output the retrieved response as JSON-encoded string, and set an optional status code. Stops execution afterwards.
$response (any) — JSON-serializable response object
$code (int) — HTTP response status code
Check($check, $subroutes)
Wrapper for subroutes array with restricted access.
$check (callable) — callback function to check for access permission
$subroutes — see route($routes)
respond_error_if_no_other_route_matches($error)
Report error duringCheck(...)without directly stopping routing.
$error (string) — error message
Param($convert, $subroutes)
Wrapper for subroutes array to convert a parsed url parameter.
$convert (callable) — callback function to convert the latest parameter
$subroutes — see route($routes)
IntParam($subroutes)
Shorthand forParam('intval', $subroutes)
$subroutes — see route($routes)
Entity($subroutes)
Item($subroutes)
Wrapper for subroutes array to generate recommended response status codes for undefined request methods.
$subroutes — see route($routes)
set_response_headers($headers)
add_response_header($header)
Replace/add headers that are automatically applied when using respond(...).
$headers (array) — headers to replace all default/previously set headers
$header (string) — header to add
set_options($options)
Set options available in \Options.
$options (associative array) — options to set, using values from \Options as array keys
Server Configuration
Additional Request Methods
By default, most Apache configurations only allow GET and POST requests. Add the following to allow further methods (PUT, PATCH, DELETE, HEAD, OPTIONS).
# .htaccess <Limit GET POST PUT PATCH DELETE HEAD OPTIONS> Require all granted </Limit> Header always set Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"
For this to work, the httpd.conf should include
<VirtualHost ...> <Directory ...> ... AllowOverride All ...
Response Headers
Response headers can be set either via PHP, which allows to set them dynamically, e.g., to support multiple specific origins:
R\set_response_headers([ "Access-Control-Allow-Origin: $approved_request_origin", 'Access-Control-Allow-Headers: content-type', 'Content-Type: application/json; charset=UTF-8' ]);
or via .htaccess if static settings are sufficient:
Header always set Access-Control-Allow-Origin "https://your-app.domain" Header always set Access-Control-Allow-Headers "content-type" Header always set Content-Type "application/json; charset=UTF-8"
URL Syntax
Short
https://your-api.domain /v1/accounts/42
# .htaccess <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /api.php/$1 [L,QSA] </IfModule>
Medium
https://your-api.domain /api.php/v1/accounts/42
(pre-configured on most systems)
# httpd.conf <VirtualHost ...> ... AcceptPathInfo On ...
or
# .htaccess AcceptPathInfo On
Long
https://your-api.domain /api.php?request=/v1/accounts/42
(vanilla PHP)
grogorick/php-routing 适用场景与选型建议
grogorick/php-routing 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 23 次下载、GitHub Stars 达 0, 最近一次更新时间为 2023 年 06 月 21 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 grogorick/php-routing 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 grogorick/php-routing 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 23
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 7
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: Unknown
- 更新时间: 2023-06-21