PHPackages                             polymorphine/routing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. polymorphine/routing

ActiveLibrary[HTTP &amp; Networking](/categories/http)

polymorphine/routing
====================

Composite routing library for HTTP applications

0.1.5(1y ago)074MITPHPPHP ^7.4 || ^8.0

Since Mar 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/polymorphine/routing)[ Packagist](https://packagist.org/packages/polymorphine/routing)[ RSS](/packages/polymorphine-routing/feed)WikiDiscussions develop Synced 2mo ago

READMEChangelog (6)Dependencies (5)Versions (7)Used By (0)

Polymorphine/Routing
====================

[](#polymorphinerouting)

[![Latest stable release](https://camo.githubusercontent.com/ad894e35ec413f1461cb7be7755b39ac8fcd96023952ad44d5bb380db2de5d88/68747470733a2f2f706f7365722e707567782e6f72672f706f6c796d6f727068696e652f726f7574696e672f76657273696f6e)](https://packagist.org/packages/polymorphine/routing)[![Build status](https://github.com/polymorphine/routing/workflows/build/badge.svg)](https://github.com/polymorphine/routing/actions)[![Coverage status](https://camo.githubusercontent.com/503f5de4ab7fbb1942a3d609a73e884d70127d346403f59720cebfc276b89f37/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f706f6c796d6f727068696e652f726f7574696e672f62616467652e7376673f6272616e63683d646576656c6f70)](https://coveralls.io/github/polymorphine/routing?branch=develop)[![PHP version](https://camo.githubusercontent.com/f13615778655c2d0ec9d2d4e6ae471bfc54f1d79f91980a13dd91b0ba13a94b5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f706f6c796d6f727068696e652f726f7574696e672e737667)](https://packagist.org/packages/polymorphine/routing)[![LICENSE](https://camo.githubusercontent.com/e90eaba7adab17e8a5f5f240b23c76f76de902759c606cf7cc0d5248dc63f8e5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f706f6c796d6f727068696e652f726f7574696e672e7376673f636f6c6f723d626c7565)](LICENSE)

### Composite routing library for HTTP applications

[](#composite-routing-library-for-http-applications)

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

[](#concept-feature-tree-structure-routing-matching-requests-and-building-endpoint-urls)

Router may consist of individual routes (see [`Route`](src/Route.php) 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`](src/Builder.php) is a part of this package to help with the problem. It uses *fluent interface with expressive method names* - more concise than class names &amp; 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](https://getcomposer.org/)

[](#installation-with-composer)

```
composer require polymorphine/routing
```

### Routing build example

[](#routing-build-example)

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

[![Routing diagram](https://user-images.githubusercontent.com/9908030/48569332-aeb2e980-e901-11e8-810e-4e447df49ce6.png)](https://user-images.githubusercontent.com/9908030/48569332-aeb2e980-e901-11e8-810e-4e447df49ce6.png)

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`](tests/ReadmeExampleTest.php) - compare one created as above using builder ([`BuilderTests.php`](tests/ReadmeExampleTest/BuilderTest.php)) and equivalent structure composed directly from components ([`CompositionTests.php`](tests/ReadmeExampleTest/CompositionTest.php)) which will be result of calling builder methods.

### Routing components &amp; builder commands

[](#routing-components--builder-commands)

#### Endpoints

[](#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`](src/Route/Endpoint/CallbackEndpoint.php) ([`RouteBuilder::callback($callable)`](src/Builder/Node/RouteNode.php#L47)) will handle forwarded request using given callback function with following signature: ```
    $callable = function (ServerRequestInterface $request): ResponseInterface { ... }
    ```
2. [`HandlerEndpoint`](src/Route/Endpoint/HandlerEndpoint.php) ([`RouteBuilder::handler(RequestHandlerInterface $handler)`](src/Builder/Node/RouteNode.php#L59)) will handle forwarded request with given class implementing RequestHandlerInterface.
3. [`RedirectEndpoint`](src/Route/Endpoint/RedirectEndpoint.php) ([`RouteBuilder::redirect(string $routingPath, $code = 301)`](src/Builder/Node/RouteNode.php#L84)) will return response redirecting to another endpoint route.
4. *Mapped endpoint* ([`RouteBuilder::endpoint(string $id)`](src/Builder/Node/RouteNode.php#L104)) will use user defined callback to create endpoint route based on given id string. To define mapping procedure initialise [`Builder`](src/Builder.php) with [`MappedRoutes`](src/Builder/MappedRoutes.php)with defined `$endpoint` parameter (see predefined mapping using PSR's `ContainerInterface` in [`MappedRoutes::withContainerMapping()`](src/Builder/MappedRoutes.php#L56)).

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance42

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~285 days

Recently: every ~225 days

Total

6

Last Release

472d ago

PHP version history (2 changes)0.1.0PHP ^7.4

0.1.1PHP ^7.4 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/5b83b30083b2ca0951558f0516ded598877c690f2be60cf949d9be3fdf0389ca?d=identicon)[shudd3r](/maintainers/shudd3r)

---

Top Contributors

[![shudd3r](https://avatars.githubusercontent.com/u/9908030?v=4)](https://github.com/shudd3r "shudd3r (488 commits)")

---

Tags

httppsr-15psr-7routing

### Embed Badge

![Health badge](/badges/polymorphine-routing/health.svg)

```
[![Health](https://phpackages.com/badges/polymorphine-routing/health.svg)](https://phpackages.com/packages/polymorphine-routing)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5723.1M30](/packages/thecodingmachine-graphqlite)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28483.0k2](/packages/mezzio-mezzio-authentication-oauth2)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)[windwalker/framework

The next generation PHP framework.

25639.1k1](/packages/windwalker-framework)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
