vakata/httprouter

路由类的扩展实现,处理HTTP抽象和中间件。

3.0.3 2016-10-27 11:39 UTC

This package is auto-updated.

Last update: 2024-09-10 05:20:54 UTC


README

Latest Version on Packagist Software License Build Status Code Climate Tests Coverage

路由类的扩展实现,处理HTTP抽象和中间件。

安装

通过Composer

$ composer require vakata/httprouter

用法

// create an instance
$httprouter = new \vakata\httprouter\HttpRouter();
$httprouter
    ->get('/', function () { echo 'homepage'; })
    ->get('/profile', function () { echo 'user profile'; })
    ->group('/books/', function ($httprouter) { // specify a prefix
        $httprouter
            ->get('read/{i:id}', function ($matches) {
                // this method uses a named placeholder
                // when visiting /books/read/10 matches will contain:
                var_dump($matches); // 0 => books, 1 => read, 2 => 10, id => 10
                // placeholders are wrapped in curly braces {...} and can be: 
                //  - i - an integer
                //  - a - any letter (a-z)
                //  - h - any letter or integer
                //  - * - anything (up to the next slash (/))
                //  - ** - anything (to the end of the URL)

                // placeholders can be named too by using the syntax:
                // {placeholder:name}
                
                // placeholders can also be optional
                // {?optional}
            })
            // for advanced users - you can use any regex as a placeholder:
            ->get('{(delete|update):action}/{(\d+):id}', function ($matches) { })
            // you can also use any HTTP verb
            ->post('delete/{i:id}', function ($matches) { })
    })
    // you can also bind multiple HTTP verbs in one go
    ->add(['GET', 'HEAD'], '/path', function () { });

// there is no need to chain the method calls - this works too:
$httprouter->post('123', function () { });
$httprouter->post('456', function () { });

// you finally run the httprouter
try {
    $httprouter->run(
        parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),
        $_SERVER['REQUEST_METHOD']
    );
} catch (\vakata\router\RouterNotFoundException $e) {
    // thrown if no matching route is found
}

API文档中了解更多

测试

$ composer test

贡献

请查看CONTRIBUTING以获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件github@vakata.com联系,而不是使用问题跟踪器。

致谢

许可证

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