memcrab / exceptions
基于 PHP 的 Exceptions 库,用于 memCrab Core API
1.1.1
2021-08-25 12:53 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: 6.*.*
This package is auto-updated.
Last update: 2024-09-25 20:10:50 UTC
README
状态
这是一个基于 yaml 配置文件和 PHP 路由器的 PHP 路由器,每个路由条件都支持正则表达式。这有助于仅使用数字作为 URL 的一部分或使用所需单词的一部分等,以构建更准确的路由。
特性
- 支持任何类型的路由中的 RegExp
- 支持单个 URL 的多路由,通过不同的请求方法(POST、GET、PUT、DELETE 等)
- 支持完整 URL 或仅请求 URI
- 所有配置都在简单的 YAML 文件中
- 每个路由可以返回已命名的参数(你想要多少个参数,或者正则表达式中有多少个参数)
- 使用更新的 pecl yaml-ext 2.0.0 为 PHP 7.0 进行高性能 yaml 解析
- 使用 PHP 7.1 的严格标准编码和参数及返回值的完整类型检查
- PSR-4 自动加载兼容的结构
- 使用 PHPUnit 进行单元测试
- 易于在任何框架中使用
安装
composer require memcrab/router
依赖
php 扩展 YAML
- 对于 Ubuntu/Debian
- apt-get update
- apt-get install php-pear
- apt-get install php-dev
- apt-get install php-xml php7.0-xml
- apt-get install libyaml-dev
- pecl channel-update pecl.php.net
- pecl install yaml-2.0.0
- 对于 OS X
- brew install php71 --with-pear
- brew install autoconf
- touch $(brew --prefix php71)/lib/php/.lock && chmod 0644 $(brew --prefix php71)/lib/php/.lock
- pecl install yaml-2.0.0
用法
- 初始化路由器:
memCrab\Router()
- 加载路由:
->loadRoutesFromYaml(string $filePath)
- $filePath - 路由 yaml 文件的路径
- 运行匹配:
->matchRoute(string $url, string $method)
- $url - URL(《http://example.com/posts》)或页面请求 URI(《/post》)
- $method - HTTP 请求方法
- 使用以下方式使用你的路由数据:
- getService() - 返回我们调用的组件
- getAction() - 返回将从组件中运行的动作
- getParams() - 返回路由正则表达式参数
YAML 配置示例
routes: /: GET: [Index, getMain] /post/: GET: [Post, get] POST: [Post, add] PATCH: [Post, save] DELETE: [Post, delete] /post/publish/: POST: [Post, setPublishing] /catalog/([a-zA-Z0-9]+)-([a-zA-Z0-9]+)/: GET: [Catalog, filter, key1, value1]
运行示例
require_once __DIR__ . "/../vendor/autoload.php"; use memCrab\Router\Router; use memCrab\Router\RouterException; try { # Initialize Router $Router = new Router(); $Router->loadRoutesFromYaml("../src/routs.example.yaml"); # Routing $Router->matchRoute("http://example.com/post/", "POST"); # Run your Controller|Service|Component $ServiceName = $Router->getService(); $Service = new $ServiceName(); $Action = $Router->getAction(); $Response = $Service->$Action($Router->getParams()); } catch(RouterException $error){ $Response = new \YourResponseClass(); $Response->setErrorResponse($error); } $Response->sendHeaders(); $Response->sendContent();
待办事项
- 添加对后缀的支持 - URI 中不参与路由的右侧部分,例如 .html、.php、最后一个 "/" 等
- 添加对前缀的支持 - URI 中不参与路由的左侧部分,例如语言部分(uk/us/fr/ru)或地理部分(europe/asia)等
MIT 许可