Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork0
License
chimeraphp/routing
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The term Chimera (/kɪˈmɪərə/ or/kaɪˈmɪərə/) has come to describe anymythical or fictional animal with parts taken from various animals, or todescribe anything composed of very disparate parts, or perceived as wildlyimaginative, implausible, or dazzling.
There are many many amazing libraries in the PHP community and with the creationand adoption of the PSRs we don't necessarily need to rely on full stackframeworks to create a complex and well designed software. Choosing whichcomponents to use and plugging them together can sometimes be a littlechallenging.
The goal of this set of packages is to make it easier to do that (withoutcompromising the quality), allowing you to focus on the behaviour of yoursoftware.
This particular package provides PSR-15middleware and reusablerequesthandlers that help you to expose command and query handlers using HTTP as theweb mechanism.
You probably won't depend directly on this package, but it is available onPackagist, and can be installed it usingComposer:
composer require chimera/routing
In order to make sure that we're dealing with the correct data, we're usingassert(),which is a very interesting feature in PHP but not often used. The nice thingaboutassert() is that we can (and should) disable it in production mode sothat we don't have useless statements.
So, for production mode, we recommend you to setzend.assertions to-1 in yourphp.ini.For development you should leavezend.assertions as1 and setassert.exception to1, whichwill make PHP throw anAssertionErrorwhen things go wrong.
Check the documentation for more information:https://secure.php.net/manual/en/function.assert.php
The packages that extend this library should implement two basic interfaces, they'reused to abstract how each routing library works:
Chimera\Routing\RouteParamsExtractor: returns the list of parametersof the matched routeChimera\Routing\UriGenerator: generate routes based on the givenarguments
This middleware uses an implementation ofChimera\Routing\RouteParamsExtractorto put the parameters of the matched route in a standard attribute, so that other componentscan retrieve them.
Chimera\Handler\CreateAndFetch: executes a command to create aresource and immediately a query, returning an unformatted response with thequery result and location header - intended to be used to handlePOSTrequestsChimera\Handler\CreateOnly: executes a command to create a resource,returning an empty response with the location header - intended to be used tohandlePOST requests (variation of the previous one but can also be usedin asynchronous APIs)Chimera\Handler\ExecuteAndFetch: executes a command to modify aresource and immediately a query, returning an unformatted response with thequery result - intended to be used to handlePUT orPATCH requestsChimera\Handler\ExecuteOnly: executes a command to modify or removea resource, returning an empty response - intended to be used tohandlePUT,PATCH, orDELETE requests (can also be used inasynchronous APIs)Chimera\Handler\FetchOnly: executes a query to fetch a resource,returning an unformatted response with the query result - intended to be usedto handleGET requests
As mentioned above content negotiation is not a responsibility of the requesthandlers. It's expected that you configurelcobucci/content-negotiation-middlewareto process such task and it should be put in the very beginning of the pipeline,so that it can processany unformatted response.
TheChimera\Routing\RouteParamsExtractor middleware should be putright after the middleware responsible for matching routes (which changes foreach implementation).
So a middleware pipeline in aZend Expressive v3 applicationwould look like this - considering that all services are properly configured inthe DI container:
<?phpdeclare(strict_types=1);useChimera\Routing\RouteParamsExtraction;useLcobucci\ContentNegotiation\ContentTypeMiddleware;usePsr\Container\ContainerInterface;useZend\Expressive\Application;useZend\Expressive\Handler\NotFoundHandler;useZend\Expressive\Helper\BodyParams;useZend\Expressive\Helper\ServerUrlMiddleware;useZend\Expressive\Helper\UrlHelperMiddleware;useZend\Expressive\MiddlewareFactory;useZend\Expressive\Router\Middleware\DispatchMiddleware;useZend\Expressive\Router\Middleware\ImplicitHeadMiddleware;useZend\Expressive\Router\Middleware\ImplicitOptionsMiddleware;useZend\Expressive\Router\Middleware\MethodNotAllowedMiddleware;useZend\Expressive\Router\Middleware\RouteMiddleware;useZend\Stratigility\Middleware\ErrorHandler;returnfunction (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);};
The main idea of this package is to move your application's behaviour to thecommand and query handlers, which allows them to be reused by different deliverymechanism. This means that the logic of the request handlers are pretty muchreusable, therefore you end up having less code to maintain.
Considering that you have configured the command and query buses with the correcthandlers and also that you have mapped the instances of the request handlers in yourdependency injection container, you just need to configure the PSR-15 router to addthe handlers to the correct endpoint.
In aZend Expressive v3 applicationtheconfig/routes.php would look like this:
<?phpdeclare(strict_types=1);usePsr\Container\ContainerInterface;useZend\Expressive\Application;useZend\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 * ); */returnfunction (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');};
MIT, seeLICENSE.
About
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors7
Uh oh!
There was an error while loading.Please reload this page.