marceauka/router
Composer 安装命令:
composer require marceauka/router
包简介
Simple PHP Router with no dependencies
README 文档
README
Router is a lightweight HTTP resquest router written in PHP.
It will be your perfect companion if you need a simple and effective library or if you want an easy to understand routing library.
Otherwise, take a look at these awesome libraries symfony/routing ou league/route.
Installation
Router can be installed with composer: composer require marceauka/router.
For now, it requires PHP 7.4 or 8.0.
Also, copy / paste src/Router.php where you want and require it.
Configure Apache
The router works perfectly with any kind of URL, but if you want some url rewriting, you can use this example .htaccess.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Usage
Instanciation
Router as no params.
$router = new Router;
Adding routes
Once you have the instance, adding routes is childish.
// Will respond to : /hello (en GET) $router->get('hello', function () { echo 'Hello world!'; });
Your routes can follow these HTTP verbs: POST, PUT, PATCH and DELETE.
// POST request $router->post(...); // PATCH request $router->patch(...);
A route can use many HTTP verbs:
// GET and POST requests $router->add(['GET', 'POST'], 'hello', ...); // ... Or all HTTP verbs $router->any('hello', ...);
Finally, routes can be chained or added with a callback:
// Chaining $router->get('foo', ...)->get('bar', ...); // ...or via a callback $router->routes(function ($router) { // Votre logique });
If no callback is given to the routes() method, all routes will be returned.
$router->get('hello', ...); var_dump($router->routes()); // Returns [1 => ['uri' => 'hello', 'action' => '...']]
Listening requests
For everything to work, Router needs to incoming requests:
// Will use REQUEST_URI and REQUEST_METHOD $router->listen(); // You can spoof them with your own logic (Request library for example). $router->listing('request', 'method');
Dispatching actions
Obviously, for each route, a need. You need to define an action for each of them.
- A callback :
$router->get('hello', function () { echo 'Hello!'; })
- A class (controller, ...) :
$router->get('hello', 'MyClass@myMethod');
Here, the route, once matched, will instanciate the class named "MyClass" and will call the "myMethod" method.
Note: Router will accepts namespaces if you application can autoload them (PSR-4, ...).
$router->get('route-namespace', 'App\Http\Controller@myMethod');
Besides, you can define a global namespace for all of your actions.
// Will call App\Http\Controller\Account@resume() $router->namespaceWith('App\Http\Controller')->get('mon-account', 'Account@resume');
You can define a not found action when no routes was matched.
$router->whenNotFound(function () { echo 'Page not found'; });
URL parameters
Your routes can contains dynamic parameters. Usage is simple.
// Autorise "profile/1" or "profile/12" but not "profile/john". $router->get('profile/{:num}', ...);
Parameters can be:
- {:num} for a numeric value
- {:alpha} for a alpha value
- {:any} for all kinds of chars
- {:slug} for numbers, alpha, dash (-) and arobase (@)
Once matched, parameters are sent to the corresponding action in the URL defined order.
$router->get('profile/{:num}/{:alpha}', function ($id, $name) { echo "My name is $name and my ID is $id !"; });
Named routes
You can give a name to your routes to access them later or easily creating links (in a view for example).
$router->get('/homepage', '...', 'home'); $router->link('home'); // Returns "/homepage"
If your route contains parameters, you can build an URI with filled parameters.
You need to give all parameters expected by the route, otherwise and exception will be rised.
$router->get('/tag/{:slug}', '...', 'tag'); $router->link('tag', 'wordpress'); // => Returns "/tag/wordpress" $router->get('/user/{:num}/{:any}', '...', 'profile'); $router->link('profile', [42, 'JohnDoe']); // => Returns "/user/42/JohnDoe"
Caching
Sometimes, when our router contains many routes, it's convenient to have a ready-to-use Router instance for each script execution. Router supports serialization and unserialization. Two helpers exists to assists you.
- Export the configured instance:
$compiled = $router->getCompiled(); // Retourns a string
- Import a configured instance:
$router = MarceauKa\Router::fromCompiled($compiled); // Returns the instance previously configured
Note: Routes using a callback can't be serialized. Only the "MyClass@myMethod" is serializable.
The router does not provide functionnality to store or read a cache file. It's not its goal.
Tests
Tests are with PHPUnit 9. You can use the phpunit command given at vendor/bin.
vendor/bin/phpunit
Tests are certainly incomplete. Feel free to contribute.
Licence
MIT
marceauka/router 适用场景与选型建议
marceauka/router 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 115 次下载、GitHub Stars 达 8, 最近一次更新时间为 2020 年 12 月 15 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「http」 「rest」 「library」 「router」 「routes」 「Simple」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 marceauka/router 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 marceauka/router 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 marceauka/router 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
A PSR-7 compatible library for making CRUD API endpoints
Api bundle
Inbox pattern process implementation for your Laravel Applications
Core library that defines common interfaces used by the rest of the intahwebz..
Amqp classes
统计信息
- 总下载量: 115
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 8
- 点击次数: 4
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-12-15