kit92/epicroute

非常快速的请求路由器

1.0.0 2017-03-02 12:38 UTC

This package is not auto-updated.

Last update: 2024-09-18 20:17:49 UTC


README

使用这个库,您可以在PHP应用程序中轻松实现路由,并且它的速度非常快!

安装

使用composer安装

composer require kito92/epicroute

需要PHP 5.3+。

基本用法

简单的文件设置位于 'example' 目录下。以下是一个基本用法示例

<?php
require 'vendor/autoload.php';
$route = \EpicRoute\Route::getInstance();

$route->get('/', function(){
    echo 'response';
});

$route->dispatch();

可用的方法如下

$route->get('/...', function(){ /*...*/ });
$route->post('/...', function(){ /*...*/ });
$route->put('/...', function(){ /*...*/ });
$route->patch('/...', function(){ /*...*/ });
$route->delete('/...', function(){ /*...*/ });

变量 & 正则表达式

以下是匹配变量的方法

$route->get('/users/:name', function($name){
    echo 'Welcome back ' . $name;
});

并且这样您可以只匹配数值

$route->get('/users/:id{[0-9]*}', function($id){
    echo 'user id ' . $id;
});

要匹配所有子URL,您可以在变量名称的末尾添加"+"

$route->get('/:slug+', function($paths){
    print_r($paths);
});

这将匹配 /any/route/you/goes,并且变量 $paths 是一个包含请求子文件夹的数组。

请记住,对于相同的base url,如果您有多个正则路由和一个通用路由,您必须先声明那些有正则的路由,然后是通用路由,否则路由器总是会提供通用路由。您可以通过流畅的接口调用多个方法。因此,例如

$route->get('/users/:id{[0-9]*}', function($id){ /*...*/ })
	  ->get('/users/:name', function($name){ /*...*/ })
	  ->dispatch();

中间件

您可以通过实现 \EpicRoute\Middleware 接口来定义您的自定义中间件

class CustomMiddleware implements \EpicRoute\Middleware{
    /**
     * This method will be executed before the routing
     *
     * @return mixed
     */
    function before(){
        // TODO: Implement before() method.
    }

    /**
     * This method will be executed after the routing
     *
     * @return mixed
     */
    function after(){
        // TODO: Implement after() method.
    }
}

并且您可以通过这种方式将中间件与路由关联起来

$route->get('/', function(){
    echo 'home';
}, ['middleware' => CustomMiddleware::class]);

分组

如果您想将中间件设置为一组路由,您可以声明一个视图组

$route->group(['middleware' => CustomMiddleware::class], function () use ($route){
    $route->get('/users/:id{[0-9]*}', function ($id){
        echo 'user id ' . $id;
    });
    $route->get('/users/:name', function ($name){
        echo 'Welcome back ' . $name;
    });
})->dispatch();

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。