moxxie / moxrouter
0.2.6
2019-09-08 09:29 UTC
README
一个简单快速的PHP路由器
安装
建议使用 Composer 安装 MoxRouter。
$ composer require moxxie/moxrouter "^0.2.0"
使用
入门
创建一个包含以下内容的 index.php 文件
<?php require 'vendor/autoload.php'; $router = new Moxxie\MoxRouter(); $router->get('/{message}', function($message){ echo "Hello " . $message . "!"; }); $router->run();
您可以使用PHP自带的内置服务器进行测试
$ php -S localhost:8000
https://:8000/world 将会显示 "Hello, world!"。
路由请求
MoxRouter 支持GET、POST、PUT、PATCH和DELETE HTTP请求
// Will only match GET HTTP requests $router->get('/product/{id}', function($id){ // Return product with id = $id }); // Will only match POST HTTP requests $router->post('/product', function(){ // Create new a product }); // Will only match PUT HTTP requests $router->put('/product/{id}', function($id){ // Update product with id = $id }); // Will only match PATCH HTTP requests $router->patch('/product/{id}', function($id){ // Apply changes made to product with id = $id }); // Will only match DELETE HTTP requests $router->delete('/product/{id}', function($id){ // Delete product with id = $id });
服务容器
<?php $router = new Moxxie\MoxRouter(); // Create an empty container $container = []; // Add a service to the container $container['service'] = function(){ return new Service(); }; $router->get('/', function(){ // Use the new Service $service = $this->service(); }); // Run the router with the container $router->run($container);
钩子
路由前
$router->before(function(){ // This code will be executed before a route has been executed });
路由后
$router->after(function(){ // This code will be executed after a route has been executed });
未找到(404)
您可以覆盖默认的404处理器
$router->notFound(function(){ // This code will be executed when a route is not found });
重写所有请求到 MoxRouter
Apache .htaccess
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php [L]
Nginx
try_files $uri /index.php;
许可证
(MIT许可证)
版权(c)2017 Moxxie - https://github.com/Moxxie/MoxRouter
在此特此授予任何人获得本软件及其相关文档副本(以下简称“软件”)的权利,免费使用该软件,不受限制,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本的权利,并允许向提供软件的个人授予此类权利,但需遵守以下条件
上述版权声明和本许可声明应包含在软件的所有副本或实质性部分的副本中。
软件按“原样”提供,不提供任何形式的保证,无论是明示的、暗示的,包括但不限于适销性、针对特定目的的适用性和非侵权性保证。在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任承担责任,无论该责任是因合同、侵权或其他方式引起的,是否与软件或其使用或与其他方式有关。