定制 polymorphine/routing 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

polymorphine/routing

Composer 安装命令:

composer require polymorphine/routing

包简介

Composite routing library for HTTP applications

README 文档

README

Latest stable release Build status Coverage status PHP version LICENSE

Composite routing library for HTTP applications

Concept feature: Tree structure routing matching requests and building endpoint urls

Router may consist of individual routes (see Route interface) of three main categories:

  • Splitters - Switches that branch single route into multiple route paths. Switch would be more accurate name, but it's a php keyword and it would require some additional prefix/postfix description.
  • Gates - Routes that determine if current request should be forwarded or performs some preprocessing based on request passing through.
  • Endpoints - Routes which only responsibility is to take (processed) request and pass it to handler that produces response. Neither routing path continuations nor uri building happens in endpoint routes, but when request uri path is not fully processed then handler method is not called and null (prototype) response is returned. Endpoints are also capable of gathering and returning responses for OPTIONS method requests if this http method was not explicitly routed.

These routes composed in different ways will create unique routing logic, but since composition tree may be deep its instantiation using new operator may become hard to read by looking at large nested structure or its dependencies assembled together, but instantiated in order that is reversed to execution flow (nested structure instantiated first).

Builder is a part of this package to help with the problem. It uses fluent interface with expressive method names - more concise than class names & their constructors that would be used in direct composition. It is also more readable due to the fact that builder method calls resemble execution path in instantiated tree.

Installation with Composer

composer require polymorphine/routing

Routing build example

Diagram below shows control flow of the request passed to matching endpoint in simplified blog page example.

Routing diagram

Let's start with it's routing logic description:

  1. Request is passed to the router (root)
  2. Forwarded request goes through CSRF and (if CSRF guard will allow) Authentication gates (let's assume that there are no other registered user roles than admin)
  3. In ResponseScan request is forwarded sequentially through each route until response other than "nullResponse" is returned.
  4. First (default) route will pass request forward only if Authentication marked request as coming from page admin.
  5. If request was forwarded all meaningful endpoints are available, and if user has no authenticated account routes dedicated for unregistered ("guest") user are tested.
  6. Of course "guest" user may access almost all pages in read-only mode, so we can forward his request to the main tree after guest specific or forbidden options are excluded. Next routes will check if user wants to log in, access logout page (which makes no sense so he is redirected) or gain unauthorized access to /admin path. Beside these, all other read-only (GET) endpoints should be accessible for guests.
  7. If none of previous routes returned meaningful response GET requests are allowed to main endpoints tree.
  8. While some endpoint access makes sense from guest perspective it is pointless from admin's - for example admin trying to log in will be redirected to home page. Guests won't be forwarded here, because this case was already resolved for them.

Here's an example showing how to create this structure using routing builder:

/**
 * assume defined:
 * UriInterface        $baseUri
 * ResponseInterface   $nullResponse
 * MiddlewareInterface $csrf
 * MiddlewareInterface $auth
 * callable            $adminGate
 * callable            $notFound
 * callable            $this->endpoint(string)
 */

$builder = new Builder();
$root    = $builder->rootNode()->middleware($csrf)->middleware($auth)->responseScan();

$main = $root->defaultRoute()->callbackGate($adminGate)->link($filteredGuestRoute)->pathSwitch();
$main->root('home')->callback($this->endpoint('HomePage'));
$admin = $main->route('admin')->methodSwitch();
$admin->route('GET')->callback($this->endpoint('AdminPanel'));
$admin->route('POST')->callback($this->endpoint('ApplySettings'));
$main->route('login')->redirect('home');
$main->route('logout')->method('POST')->callback($this->endpoint('Logout'));
$articles = $main->resource('articles')->id('id');
$articles->index()->callback($this->endpoint('ShowArticles'));
$articles->get()->callback($this->endpoint('ShowArticle'));
$articles->post()->callback($this->endpoint('AddArticle'));
$articles->patch()->callback($this->endpoint('UpdateArticle'));
$articles->delete()->callback($this->endpoint('DeleteArticle'));
$articles->add()->callback($this->endpoint('AddArticleForm'));
$articles->edit()->callback($this->endpoint('EditArticleForm'));

$root->route()->path('/login')->methodSwitch([
    'GET'  => new CallbackEndpoint($this->endpoint('LoginPage')),
    'POST' => new CallbackEndpoint($this->endpoint('Login'))
]);
$root->route()->path('/logout')->redirect('home');
$root->route()->path('/admin')->redirect('login');
$root->route()->method('GET')->joinLink($filteredGuestRoute);
$root->route()->callback($notFound);

$router = $builder->router($baseUri, $nullResponse);

Tests for this example structure can be found in ReadmeExampleTests.php - compare one created as above using builder (BuilderTests.php) and equivalent structure composed directly from components (CompositionTests.php) which will be result of calling builder methods.

Routing components & builder commands

Endpoints

Endpoints are responsible for handling incoming server requests with procedures given by programmer. Beside that, endpoints can can handle types of requests that can be resolved in generic way (OPTIONS, HEAD). There are several ways to define endpoint behaviour:

  1. CallbackEndpoint (RouteBuilder::callback($callable)) will handle forwarded request using given callback function with following signature:
    $callable = function (ServerRequestInterface $request): ResponseInterface { ... }
  2. HandlerEndpoint (RouteBuilder::handler(RequestHandlerInterface $handler)) will handle forwarded request with given class implementing RequestHandlerInterface.
  3. RedirectEndpoint (RouteBuilder::redirect(string $routingPath, $code = 301)) will return response redirecting to another endpoint route.
  4. Mapped endpoint (RouteBuilder::endpoint(string $id)) will use user defined callback to create endpoint route based on given id string. To define mapping procedure initialise Builder with MappedRoutes with defined $endpoint parameter (see predefined mapping using PSR's ContainerInterface in MappedRoutes::withContainerMapping()).

polymorphine/routing 适用场景与选型建议

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-06-08