PHPackages                             ignaszak/router - 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. ignaszak/router

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

ignaszak/router
===============

Simple object oriented PHP Router

v2.1.1(10y ago)0233MITPHPPHP &gt;=7.0

Since Dec 12Pushed 8y ago1 watchersCompare

[ Source](https://github.com/ignaszak/php-router)[ Packagist](https://packagist.org/packages/ignaszak/router)[ RSS](/packages/ignaszak-router/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (3)Versions (9)Used By (0)

ignaszak/router
===============

[](#ignaszakrouter)

[![Build Status](https://camo.githubusercontent.com/99c8e3e93da5724a6436054b39d1f44326fa7f882ac727a736289abb88aaac92/68747470733a2f2f7472617669732d63692e6f72672f69676e61737a616b2f7068702d726f757465722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/ignaszak/php-router) [![Coverage Status](https://camo.githubusercontent.com/f55f3c40ca9c16350dd4df07d463eff3ffa00de8c9d693fc835b0a563ed59997/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f69676e61737a616b2f7068702d726f757465722f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/ignaszak/php-router?branch=master)

Simple object oriented PHP Router

Installing
----------

[](#installing)

The package is available via [Composer/Packagist](https://packagist.org/packages/ignaszak/router), so just add following lines to your composer.json file:

```
{
    "require" : {
        "ignaszak/router" : "*"
    }
}
```

or:

```
php composer.phar require ignaszak/router
```

Configuration
-------------

[](#configuration)

The easiest way is to configure mod\_rewrite via .htaccess file in site base directory. Example:

```
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L]

```

Running Tests
-------------

[](#running-tests)

Just run phpunit from the working directory

```
php phpunit.phar
```

Usage
-----

[](#usage)

### Demo

[](#demo)

```
use Ignaszak\Router\Collection\Route;
use Ignaszak\Router\Matcher\Matcher;
use Ignaszak\Router\Host;
use Ignaszak\Router\Response;

include __DIR__ . '/vendor/autoload.php';

// Define routes
$route = Route::start();
$route->add('name', '/test/{test}/{id}/{globlToken}', 'GET|POST')
    ->tokens([
        'test' => '(\w+)',
        'id' => '(\d+)'
    ]);
$route->get('get', '/get/test')->controller('AnyController');
$route->post('post', '/post/{name}')
    ->tokens(['name' => '([a-z]+)'])
    ->defaults(['name' => 'demo'])
    ->attach(function ($name) {
        echo $name;
    });
$route->addTokens(['globalToken' => '([0-9]+)']);

// Match routes
$matcher = new Matcher($route);
$response = new Response($matcher->match(new Host()));
$response->all();
```

### Create routes

[](#create-routes)

#### Add routes

[](#add-routes)

```
use Ignaszak\Router\Collection\Route;

include __DIR__ . '/vendor/autoload.php';

$route = Route::start();

// Define name (is not required but if is defined it must be unique for each defined routes),
// pattern and http method (it is possible to combine all http methods e.g.:
// 'GET|POST', not required, if is empty - route match for all methods).
$route->add('name', '/test/(\w+)/', 'GET');

// There are two more add methods:
$route->get(null, '/match/only/get');
$route->post(null, '/match/only/post');
```

#### Add tokens

[](#add-tokens)

```
$route->add(null, '/test/{test}/{name}/{id}')->tokens([
    'test' => '(\w+)',
    'name' => '(\w+)',
    'id' => '(\d+)'
]);
```

#### Define default values

[](#define-default-values)

```
$route->add(null, '/test/{test}/{name}/{id}')->tokens([
    'name' => '(\w+)'
])->defaults([
    'name' => 'test'
]);
```

#### Add controller

[](#add-controller)

```
$route->add('user', '/user')->controller('UserController');

// Define controller from route
$route->add(null, '/test/{controller}/{action}')
    ->controller('\\Namespace\\{controller}::{action}')
    ->tokens([
        'controller' => '([a-zA-Z]+)',
        'action' => '([a-zA-Z]+)'
    ]);
```

#### Add attachment

[](#add-attachment)

```
use Ignaszak\Router\IResponse;

$route->add('attach', '/attach/{name}/(\w+)/{id}/')
    ->tokens([
        'name' => '(\w+)',
        'id' => '(\d+)'
    ])->attach(function (IResponse $response) {
        // IResponse interface - described in 'Get response' section
        print_r($response->all());
    });
```

#### Group routes

[](#group-routes)

```
// Every added route after this method will be in the same group
$route->group('groupName');
// Disable group
$route->group();
```

#### Add defined patterns

[](#add-defined-patterns)

Router provides some defined regular expressions such as:

- *@base* - use to define default route
- *@notfound* - not found
- *@digit* - digits \[0-9\]
- *@alpha* - alphabetic characters \[A-Za-z\_-\]
- *@alnum* - alphanumeric characters \[A-Za-z0-9\_-\]

```
$route->add('defined', '/regex/@alpha/{id}')->tokens(['id' => '@digit']);

// Add default route
$route->add('default', '/@base')->controller('DefaultController');

// Not found
$route->add('error', '/@notfound')->attach(function () {
    throw new Exception('404 Not Found');
});
```

#### Add global tokens and patterns

[](#add-global-tokens-and-patterns)

Global tokens and patterns are avilable for all routes

```
// Global tokens
$route->addTokens([
    'slug' => '(\w+)',
    'user' => '(\w+)',
    'page' => '(\d+)'
]);
// Define default values for global tokens
$route->addDefaults([
    'slug' => 'test',
    'user' => 'demo',
    'page' => 1
]);

// Create new patterns
$route->addPatterns([
    'day' => '([0-9]{2})',
    'month' => '([0-9]{2})',
    'year' => '([0-9]{4})'
]);
// Example: $route->add(null, '/@year/@month/@day/');
```

### Match routes

[](#match-routes)

```
use Ignaszak\Router\Collection\Route;
use Ignaszak\Router\Matcher\Matcher;
use Ignaszak\Router\Host;

include __DIR__ . '/autoload.php';

$route = Route::start();
/* Define routes */

// Add defined routes to matcher
$matcher = new Matcher($route);
// Match routes with Host class
$matcher->match(new Host());
// Or define custom request and http method
$matcher->match(null, '/custom/request', 'GET');
```

##### Host class

[](#host-class)

```
new Host([string $baseQuery]);
```

Class provides current request and http method. Argument *$baseQuery* defines folder via site is avilable e.g.: `http://localhost/~user/ => $baseQuery = /~user` (without trailing slash).

#### Get response

[](#get-response)

```
use Ignaszak\Router\Collection\Route;
use Ignaszak\Router\Matcher\Matcher;
use Ignaszak\Router\Host;
use Ignaszak\Router\Response;

$route = Route::start();
/* Define routes */

$matcher = new Matcher($route);
/* Match routes */

// Get response
$response = new Response($matcher->match(new Host()));

// Get route name
$response->name();
// Get route controller
$response->controller();
// Get route group
$response->group();
// Get matched params in array
$response->all();
// Get param by token
$response->get(string $token [, $default = null]);
// Get tokens array
$response->tokens();
// Returns true if the token is defined
$response->has(string $token);
```

#### Reverse Routing

[](#reverse-routing)

Url can be generated for any defined route with name by using `UrlGenerator(IRoute $route [, Host $host])` class.

```
use Ignaszak\Router\Collection\Route;
use Ignaszak\Router\Matcher\Matcher;
use Ignaszak\Router\Host;
use Ignaszak\Router\Response;
use Ignaszak\Router\UrlGenerator;

$route = Route::start();
/* Define routes */

$host = new Host();

$matcher = new Matcher($route);
$response = new Response($matcher->match($host));

// UrlGenerator
$url = new UrlGenerator($route, $host);
// Example route: $route->get('user', '/user/{user})->tokens(['user' => '@alnum']);
$url->url('user', ['user' => 'UserName']);
```

`UrlGenerator::url(string $name [, array $replacement])` method will return:

- if `Host` class is used: `http://servername/user/UserName`
- if `Host` class is not defined: `/user/UserName`

### Load routes from Yaml

[](#load-routes-from-yaml)

#### Yaml file example

[](#yaml-file-example)

You can define routes, global tokens and patterns. Attachment is not available in yaml file. **example.yml:**

```
routes:
    test:
        path: '/test/{controller}/{action}'
        method: GET
        controller: '\Namespace\{controller}::{action}'
        group: groupName
        tokens:
            controller: '@custom'
        defaults:
            controller: HomePageController
    default:
        path: /@base
        controller: DefaultController
    error:
        path: /@notfound
        controller: ErrorController

tokens:
    action: '@alnum'

defaults:
    action: index

patterns:
    custom: ([a-zA-Z]+)
```

#### Yaml class

[](#yaml-class)

```
use Ignaszak\Router\Collection\Yaml;
use Ignaszak\Router\Matcher\Matcher;

$yaml = new Yaml();
// Add yaml files
$yaml->add('example.yml');
$yaml->add('anotherExample.yml');

$matcher = new Matcher($yaml);
/* Match routes and get response */
```

### Cache

[](#cache)

It is possible to generate cache of routes defined in yaml file or Route class. Cache stores converted routes to regex, so it is no need to read yaml file and convert routes at every request.

```
use Ignaszak\Router\Collection\Yaml;
use Ignaszak\Router\Collection\Cache;
use Ignaszak\Router\Matcher\Matcher;

$yaml = new Yaml();
$yaml->add('example.yml');

$cache = new Cache($yaml);
$cache->tmpDir = __DIR__; // Define custom tmp dir - optional

$matcher = new Matcher($cache);
/* Match routes and get response */
```

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

Established project with proven stability

 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 ~28 days

Recently: every ~11 days

Total

6

Last Release

3669d ago

Major Versions

v1.0.0 → v2.0.02016-03-18

PHP version history (2 changes)v1.0.0PHP &gt;=5.5

v2.0.0PHP &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/a4b982f3db3ce8473e32acea07930b0e0513b0facd39726bd493abb0357fbd8c?d=identicon)[ignaszak](/maintainers/ignaszak)

---

Top Contributors

[![ignaszak](https://avatars.githubusercontent.com/u/13788056?v=4)](https://github.com/ignaszak "ignaszak (175 commits)")

---

Tags

httprouterlibraryroutingroute

### Embed Badge

![Health badge](/badges/ignaszak-router/health.svg)

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

###  Alternatives

[aura/router

Powerful, flexible web routing for PSR-7 requests.

5231.5M67](/packages/aura-router)[miladrahimi/phprouter

A powerful, lightweight, and very fast HTTP URL router for PHP projects.

20832.6k2](/packages/miladrahimi-phprouter)[pmjones/auto-route

Automatically routes HTTP request to action classes.

20158.6k6](/packages/pmjones-auto-route)[delight-im/router

Router for PHP. Simple, lightweight and convenient.

432.3k1](/packages/delight-im-router)[wilaak/radix-router

High-performance radix tree based HTTP request router

612.8k5](/packages/wilaak-radix-router)

PHPackages © 2026

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