承接 atanvarno/router 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

atanvarno/router

Composer 安装命令:

composer require atanvarno/router

包简介

FastRoute PSR-7 wrapper

README 文档

README

Software License Latest Version Build Status Coverage Status

A PSR-7 wrapper for FastRoute.

Requirements

PHP >= 7.0 is required, but the latest stable version of PHP is recommended.

Installation

$ composer require atanvarno/router:^0.2.0

Basic Usage

Two routers are provided: SimpleRouter and CachedRouter. These both implement the Router interface.

Instantiation

// A simple, non-caching, router:
use Atanvarno\Router\SimpleRouter;
$router = new SimpleRouter();

// A caching router:
use Atanvarno\Router\CachedRouter;
$router = new CachedRouter();

By default, the GroupCountBased FastRoute driver is used. Other drivers may be specified in the router constructor using the Router::DRIVER_* constants.

See SimpleRouter::__construct() and CachedRouter::__construct().

Defining routes

Routes can be defined by using the add() method, the addGroup() method or via constructor injection. There are also shortcut methods for every HTTP method.

add()

$router->add($method, $pattern, $handler);

The $method is an uppercase HTTP method string for which a certain route should match. It is possible to specify multiple valid methods using an array. There is a Router::METHOD_* constant for each valid HTTP method.

By default the $pattern uses a syntax where {foo} specifies a placeholder with name foo and matching the regex [^/]+. To adjust the pattern the placeholder matches, you can specify a custom pattern by writing {bar:[0-9]+}.

Custom patterns for route placeholders cannot use capturing groups. For example {lang:(en|de)} is not a valid placeholder, because () is a capturing group. Instead you can use either {lang:en|de} or {lang:(?:en|de)}.

Furthermore parts of the route enclosed in [...] are considered optional, so that /foo[bar] will match both /foo and /foobar. Optional parts are only supported in a trailing position, not in the middle of a route.

The $handler parameter does not necessarily have to be a callback, it could also be a controller class name or any other kind of data you wish to associate with the route. Atanvarno\Router only tells you which handler corresponds to your request, how you interpret it is up to you.

add() implements a fluent interface, allowing multiple calls to be chained.

See Router::add().

addGroup()

You can specify routes inside of a group. All routes defined inside a group will have a common prefix.

For example, defining your routes as:

$router->addGroup(
    '/admin',
    [
        [Router::METHOD_GET, '/user/{name}', 'handler']
        [Router::METHOD_DELETE, '/user/{name}', 'handler'],
    ]
);

Will have the same result as:

$router->add(Router::METHOD_GET, '/admin/user/{name}', 'handler')
    ->add(Router::METHOD_DELETE, '/admin/user/{name}', 'handler');

addGroup() implements a fluent interface, allowing multiple calls to be chained.

See Router::addGroup().

Constructor injection

Route information can be injected into the Router instance constructor. This parameter accepts an array of arrays containing $method, $pattern and $handler values, like a call to add().

This allows routes to be held in a separate configuration file that returns such an array:

<?php // routes.php
use Atanvarno\Router\Router;

return [
    [Router::METHOD_GET, '/user[/{id:\d+}[/{name}]]', 'handler'],
    [Router::METHOD_PATCH, '/table/{tid}/{uid}/{data}', 'handler'],
    //...
];
<?php // main.php
use Atanvarno\Router\{Router, SimpleRouter};

$router = new SimpleRouter(Router::DRIVER_GROUP_COUNT, include 'path/to/routes.php');

See SimpleRouter::__construct() and CachedRouter::__construct().

Shortcut methods

For all the valid HTTP request methods shortcut methods are available. For example:

$router->get('/get-route', 'get_handler')
    ->post('/post-route', 'post_handler');
// Is equivalent to:
$router->add(Router::METHOD_GET, '/get-route', 'get_handler')
    ->add(Router::METHOD_POST, '/post-route', 'post_handler');

Shortcut methods implement a fluent interface, allowing multiple calls to be chained.

See Router.

Dispatching

A request is dispatched by calling the dispatch() method. This method accepts a PSR-7 RequestInterface instance.

$request = //... define your PSR-7 request.

$result = $router->dispatch($request);

Note that all URI paths are normalised so that they have no trailing slash and begin with a leading slash. All user supplied patterns are likewise normalised.

dispatch() returns an array whose first element contains a status code. It is one of FastRoute\Dispatcher::NOT_FOUND, FastRoute\Dispatcher::METHOD_NOT_ALLOWED or FastRoute\Dispatcher::FOUND. For the method not allowed status the second array element contains a list of HTTP methods allowed for the supplied request.

NOTE: The HTTP specification requires that a 405 Method Not Allowed response include the Allow: header to detail available methods for the requested resource. Applications using Router should use the second array element to add this header when relaying a 405 response.

For the found status the second array element is the handler that was associated with the route and the third array element is a dictionary of placeholder names to their values. For example:

// Routing against GET /user/atan/42
[FastRoute\Dispatcher::FOUND, 'handler0', ['name' => 'atan', 'id' => '42']]

See Router::dispatch().

Caching

Instead of using SimpleRouter you can use CachedRouter.

CachedRouter requires a PSR-16 cache object as a constructor parameter.

By default, CachedRouter will take its dispatch data directly from the cache and bypass and routes defined by add() calls or constructor injection. Where no dispatch data is available (for example on the first dispatch() call or if the cache data has expired) CachedRouter will generate dispatch data from the defined routes and store it in the cache.

If your route configuration has changed and you need to update the dispatch data in the cache, call refreshCache().

See CachedRouter.

Exceptions

All exceptions thrown implement the interface RouterException.

Rather than supply array results, dispatch() can instead throw exceptions for not found and method not allowed results. MethodNotAllowedException::getAllowed() provides a list of allowed methods for the required Allow: response header.

The package contains these exceptions:

A Note on HEAD Requests

The HTTP specification requires servers to support both GET and HEAD methods:

The methods GET and HEAD MUST be supported by all general-purpose servers

To avoid forcing users to manually register HEAD routes for each resource we fallback to matching an available GET route for a given resource. Applications MAY always specify their own HEAD method route for a given resource to bypass this behavior entirely.

Full API

See API.

atanvarno/router 适用场景与选型建议

atanvarno/router 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25 次下载、GitHub Stars 达 0, 最近一次更新时间为 2017 年 03 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「router」 「FastRoute」 「psr-7」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 atanvarno/router 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 atanvarno/router 我们能提供哪些服务?
定制开发 / 二次开发

基于 atanvarno/router 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 25
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-03-15