承接 chimera/routing 相关项目开发

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

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

chimera/routing

Composer 安装命令:

composer require chimera/routing

包简介

A collection of reusable PSR-15 components that connects Chimera to any framework

README 文档

README

Total Downloads Latest Stable Version Unstable Version

Build Status Code Coverage

The term Chimera (/kɪˈmɪərə/ or /kaɪˈmɪərə/) has come to describe any mythical or fictional animal with parts taken from various animals, or to describe anything composed of very disparate parts, or perceived as wildly imaginative, implausible, or dazzling.

There are many many amazing libraries in the PHP community and with the creation and adoption of the PSRs we don't necessarily need to rely on full stack frameworks to create a complex and well designed software. Choosing which components to use and plugging them together can sometimes be a little challenging.

The goal of this set of packages is to make it easier to do that (without compromising the quality), allowing you to focus on the behaviour of your software.

This particular package provides PSR-15 middleware and reusable request handlers that help you to expose command and query handlers using HTTP as the web mechanism.

Installation

You probably won't depend directly on this package, but it is available on Packagist, and can be installed it using Composer:

composer require chimera/routing

PHP Configuration

In order to make sure that we're dealing with the correct data, we're using assert(), which is a very interesting feature in PHP but not often used. The nice thing about assert() is that we can (and should) disable it in production mode so that we don't have useless statements.

So, for production mode, we recommend you to set zend.assertions to -1 in your php.ini. For development you should leave zend.assertions as 1 and set assert.exception to 1, which will make PHP throw an AssertionError when things go wrong.

Check the documentation for more information: https://secure.php.net/manual/en/function.assert.php

Components

Extension points

The packages that extend this library should implement two basic interfaces, they're used to abstract how each routing library works:

  • Chimera\Routing\RouteParamsExtractor: returns the list of parameters of the matched route
  • Chimera\Routing\UriGenerator: generate routes based on the given arguments

Route parameters extraction middleware

This middleware uses an implementation of Chimera\Routing\RouteParamsExtractor to put the parameters of the matched route in a standard attribute, so that other components can retrieve them.

Request handlers

  • Chimera\Handler\CreateAndFetch: executes a command to create a resource and immediately a query, returning an unformatted response with the query result and location header - intended to be used to handle POST requests
  • Chimera\Handler\CreateOnly: executes a command to create a resource, returning an empty response with the location header - intended to be used to handle POST requests (variation of the previous one but can also be used in asynchronous APIs)
  • Chimera\Handler\ExecuteAndFetch: executes a command to modify a resource and immediately a query, returning an unformatted response with the query result - intended to be used to handle PUT or PATCH requests
  • Chimera\Handler\ExecuteOnly: executes a command to modify or remove a resource, returning an empty response - intended to be used to handle PUT, PATCH, or DELETE requests (can also be used in asynchronous APIs)
  • Chimera\Handler\FetchOnly: executes a query to fetch a resource, returning an unformatted response with the query result - intended to be used to handle GET requests

Usage

Middleware pipeline

As mentioned above content negotiation is not a responsibility of the request handlers. It's expected that you configure lcobucci/content-negotiation-middleware to process such task and it should be put in the very beginning of the pipeline, so that it can process any unformatted response.

The Chimera\Routing\RouteParamsExtractor middleware should be put right after the middleware responsible for matching routes (which changes for each implementation).

So a middleware pipeline in a Zend Expressive v3 application would look like this - considering that all services are properly configured in the DI container:

<?php
declare(strict_types=1);

use Chimera\Routing\RouteParamsExtraction;
use Lcobucci\ContentNegotiation\ContentTypeMiddleware;
use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\Handler\NotFoundHandler;
use Zend\Expressive\Helper\BodyParams;
use Zend\Expressive\Helper\ServerUrlMiddleware;
use Zend\Expressive\Helper\UrlHelperMiddleware;
use Zend\Expressive\MiddlewareFactory;
use Zend\Expressive\Router\Middleware\DispatchMiddleware;
use Zend\Expressive\Router\Middleware\ImplicitHeadMiddleware;
use Zend\Expressive\Router\Middleware\ImplicitOptionsMiddleware;
use Zend\Expressive\Router\Middleware\MethodNotAllowedMiddleware;
use Zend\Expressive\Router\Middleware\RouteMiddleware;
use Zend\Stratigility\Middleware\ErrorHandler;

return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
    $app->pipe(ErrorHandler::class);
    $app->pipe(ServerUrlMiddleware::class);

    // Handles content negotiation, ensuring that the response format is the best one
    // according to what was requested via the `Accept` header
    $app->pipe(ContentTypeMiddleware::class);

    $app->pipe(RouteMiddleware::class);

    // Puts the matched arguments in a standard place (must be executed after the
    // `Zend\Expressive\Router\Middleware\RouteMiddleware` middleware, otherwise
    // matched routed info is not available)
    $app->pipe(RouteParamsExtraction::class);

    // It's quite important to add this one to the list, so that we ensure
    // that the request body is properly parsed and can be retrieved via
    // `ServerRequestInterface#getParsedBody()` - used by the `HttpRequest` input
    $app->pipe(BodyParams::class);

    $app->pipe(ImplicitHeadMiddleware::class);
    $app->pipe(ImplicitOptionsMiddleware::class);
    $app->pipe(MethodNotAllowedMiddleware::class);
    $app->pipe(UrlHelperMiddleware::class);
    $app->pipe(DispatchMiddleware::class);
    $app->pipe(NotFoundHandler::class);
};

Routes

The main idea of this package is to move your application's behaviour to the command and query handlers, which allows them to be reused by different delivery mechanism. This means that the logic of the request handlers are pretty much reusable, therefore you end up having less code to maintain.

Considering that you have configured the command and query buses with the correct handlers and also that you have mapped the instances of the request handlers in your dependency injection container, you just need to configure the PSR-15 router to add the handlers to the correct endpoint.

In a Zend Expressive v3 application the config/routes.php would look like this:

<?php

declare(strict_types=1);

use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\MiddlewareFactory;

/**
 * Considering you have the following services in your DI container:
 *
 * - `album.list` => new FetchOnly(
 *     new ExecuteQuery(**query bus**, **message creation strategy**, MyApi\FetchAlbumList::class),
 *     ResponseInterface::class
 * );
 * - `album.find_one` => new FetchOnly(
 *     new ExecuteQuery(**query bus**, **message creation strategy**, MyApi\FindAlbum::class),
 *     ResponseInterface::class
 * );
 * - `album.create` => new CreateOnly(
 *     new ExecuteCommand(**command bus**, **message creation strategy**, MyApi\CreateAlbum::class),
 *     ResponseInterface::class,
 *     'album.find_one',
 *     UriGenerator::class,
 *     IdentifierGenerator::class,
 *     201
 * );
 * - `album.update_album` => new ExecuteAndFetch(
 *     new ExecuteCommand(**command bus**, **message creation strategy**, MyApi\UpdateAlbum::class),
 *     new ExecuteQuery(**query bus**, **message creation strategy**, MyApi\FindAlbum::class),
 *     ResponseInterface::class
 * );
 */
return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
    $app->get('/album', 'album.list', 'album.list');
    $app->post('/album', 'album.create', 'album.create');
    $app->get('/album/{id}', 'album.find_one', 'album.find_one');
    $app->patch('/album/{id}', 'album.update_album', 'album.update_album');
};

License

MIT, see LICENSE.

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

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 182.49k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 8
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-05-03