patrikmokry / router
一个快速的PHP路由器,支持路由参数
dev-master
2019-01-27 13:43 UTC
Requires
- php: ^7
This package is auto-updated.
Last update: 2024-09-28 01:52:13 UTC
README
一个轻量级且简单的面向对象的PHP路由器,支持控制器。
此库提供了一种基于正则表达式的快速路由实现。
使用composer轻松安装
通过composer安装
composer require patrikmokry/router
用法
示例
// index.php use PatrikMokry\Router; require_once __DIR__ . '/vendor/autoload.php'; Router::get('example', function() { return 'This route responds to requests with the GET method at the path /example'; }); Router::get('example/{id}', function($id) { return 'This route responds to requests with the GET method at the path /example/<anything>'; }); Router::get('example/{id}?', function() { return 'This route responds to requests with the GET method at the path /example/[optional]'; }); Router::post('example', function() { return 'This route responds to requests with the POST method at the path /example'; }); Router::execute(__DIR__);
// .htaccess RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.+)$ index.php [QSA,L]
定义路由
use PatrikMokry\Router; Router::get($route, $action); Router::post($route, $action); Router::put($route, $action); Router::delete($route, $action); Router::any($route, $action);
这些辅助方法是对
route($route, $action, $method = ["POST", "GET"])的封装
在PHP中,$_PUT和$_DELETE不存在,因此您必须在请求中定义名为_method的字段
正则表达式快捷方式
:i => (\d+) # numbers only
:s => (\w+) # any word, character
use in routes:
'/user/{name::i}'
'/user/{name::s}'
自定义快捷方式
Router::addShortcut(name, regex) // create shortcut with default value Router::addShortcut('locale', '(sk|en)->sk)')
反向路由的命名路由
Router::get('example/{id}', function() { return 'example'; })->name('example'); echo Router::link('example', ['id' => 48]) // example/48
前缀分组
// If you need some prefix e.g. admin, api, locale, ... Router::prefix('admin/', function() { Router::get('example/{id}', function() { return 'example'; }); });
贡献
- 将其分叉( https://github.com/MokryPatrik/PHP-Router/fork )
- 创建您的功能分支(git checkout -b my-new-feature)
- 提交您的更改(git commit -am '添加一些功能')
- 将更改推送到分支(git push origin my-new-feature)
- 创建新的拉取请求