PHPackages                             eru123/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. [Framework](/categories/framework)
4. /
5. eru123/router

ActiveLibrary[Framework](/categories/framework)

eru123/router
=============

A PHP Library for handling Routes using a Parent-Child Model

v1.0.2(2y ago)2712Apache-2.0PHP

Since Feb 7Pushed 2y ago1 watchersCompare

[ Source](https://github.com/eru123/php-router)[ Packagist](https://packagist.org/packages/eru123/router)[ RSS](/packages/eru123-router/feed)WikiDiscussions main Synced yesterday

READMEChangelog (8)DependenciesVersions (11)Used By (2)

php-router
==========

[](#php-router)

[![Build Status](https://camo.githubusercontent.com/fd7457039660692b03eacca7dbe2fb93b7f10b4ee776e5932a5c447e1a1cbf2b/68747470733a2f2f6170692e7472617669732d63692e636f6d2f6572753132332f7068702d726f757465722e7376673f6272616e63683d6d61696e)](https://app.travis-ci.com/github/eru123/php-router)[![Latest Stable Version](https://camo.githubusercontent.com/6c939ed6d2ecd070fc4963c03fe1d19d73013bc8a317c4c32a1d720743a5f47e/68747470733a2f2f706f7365722e707567782e6f72672f6572753132332f726f757465722f762f737461626c65)](https://packagist.org/packages/eru123/router)[![Total Downloads](https://camo.githubusercontent.com/5cea5b848b62fcc2aaebd54b2beb25b51e99cd356c387d83676815b95b110811/68747470733a2f2f706f7365722e707567782e6f72672f6572753132332f726f757465722f646f776e6c6f616473)](https://packagist.org/packages/eru123/router)[![License](https://camo.githubusercontent.com/6a716efb2d864c56c4fe21c8b551c5a888c0cfd777c2e30b67a77f0b71878a50/68747470733a2f2f706f7365722e707567782e6f72672f6572753132332f726f757465722f6c6963656e7365)](https://packagist.org/packages/eru123/router)

PHP Library for handling HTTP requests.

For latest documentation, please visit [Docs](https://eru123.github.io/php-router)

Supported Features
------------------

[](#supported-features)

- `URL Parameters` - Allowed dynamic parameters in the url path (ex: `/user/$id`)
- `Static Routes` - Serve static files from a directory (even forbidden directories) with directory traversal protection
- `Fallback Routes` - Fallback route for handling requests that doesn't match any other route but match the prefix url
- `Debugging` - Debug mode for debugging routes and route state
- `Route State` - Route state is passed to all route handlers and response handlers
- `Router Bootstrapper` - Allows you to run pre-handlers and allows you to manipulate the route state before the router starts running handlers
- `Route Handlers` - Route handlers are called when a route matches the request
- `Response Handlers` - Response handlers are called after the last route handler is called
- `Error Handlers` - Error handlers are called when a route handler creates a Throwable
- `Parent-Child Routes` - You can create parent-child routes for grouping routes

Basic Usage
===========

[](#basic-usage)

Install
-------

[](#install)

```
composer require eru123/router
```

Creating basic routes
---------------------

[](#creating-basic-routes)

```
 $error->getMessage(),
        'code' => $error->getCode(),
    ];

    if ($state->is_debug) {
        $result['debug'] = $state->debug;
    }

    header('Content-Type: application/json');
    print json_encode($result);
    exit;
});

// Default response and error handlers
$r->response([Builtin::class, 'response']);
$r->error([Builtin::class, 'error']);

// Create Route Request
// The first argument is the HTTP method
// The second argument is the path
// The third and so on arguments are route handlers
$r->request('GET', '/', function($state) {
    return 'Hello World!';
});

// Request Aliases
// We implement most used and common HTTP methods as aliases
$r->get($path, $handler);
$r->post($path, $handler);
$r->put($path, $handler);

// URL Parameters
// You can use URL parameters in the path with $ syntax.
// Parameter name must start with alpha and the following
// characters can be alpanumeric or underscore.
$r->get('/user/$id', function($state) {
    return 'User ID: ' . $state->params['id'];
});

// Fallback Route
// This route is called when no other route matches
// all requests with /pages as the base path will
// be handled by this route if no other route matches
$r->fallback('/pages', function($state) {
    return 'Page not found';
});

// OR Global Fallback Route
// This route is called when no other route matches
// all requests will be handled by this route if no other route matches.
// It uses a prefix url, and process the fallback route only if the URL
// matches the prefix url.
// Example:
//      $r->fallback('/pages', $handler)
//      Process all requests starting with /pages (ex: /pages/1, /pages/user/1, etc.)
$r->fallback('/', function($state) {
    return 'Page not found';
});

// Static Routes
// Static routes are routes that are intended to be used for static files.
// It can serve files from a forbidden directory that can't be accessed by
// the client. You can inject a middleware to it for checking authentication
// or etc.
// It uses a prefix url, and process the static route only if the URL
// matches the prefix url.
// For the second argument, you need to pass a directory path where the
// request file needs to be looked up.
// Example:
//      $r->static('/css', __DIR__ . '/../src/assets/css', $handler)
//      Process all requests starting with /css (ex: /css/style.css, /css/style.min.css, etc.)
$r->static('/static', __DIR__ . '/static', function($state) {
    // Check if user is authenticated
    if (!$state->user) {
        throw new \Exception('Not authenticated', 401); // this will be handled by the error handler

        // You can also return a response here if you dont want to use the error handler
        header('Content-Type: application/json');
        print json_encode([
            'error' => 'Not authenticated',
            'code' => 401,
        ]);

        exit;
    }

    // If the handler doesn't return anything, the file will be served accordingly
});
```

Advanced Usage
==============

[](#advanced-usage)

In this section, we will cover some advanced usage and in-depth details about the usage of the library.

Router paths matching order
---------------------------

[](#router-paths-matching-order)

For advanced usage, you need to understand how the router matches the request path to the route path. The router matches the request path to the route path in the following order:

- `Router::static('/', $directory[, ...$handlers])` - Routes defined using the static method are matched first.
- `Router::request($method, $path, ...$handlers)`, `Router::get($path, ...$handlers)`, `Router::post($path, ...$handlers)` - Routes defined using the request method and it's aliases are matched next.
- `Router::fallback($path, ...$handlers)` - Routes defined using the fallback method are matched last.

Regarding to order of matching inside these groups, the router matches the request path to the route path in the first come first serve order.

For example, if you have the following routes:

```
// First come first serve order

// this will be matched first, this will also match /user/me
$r->get('/user/$x', $handler1);

// this will be matched second, but it's handlers will not be
// called unless the $handler1's state called skip() method
// Example: $state->skip();
$r->get('/user/me', $handler2);

// NOTE: These kind of URL path designs are NOT RECOMMENDED.
```

Route State
-----------

[](#route-state)

`RouteState` is the class instance that is passed to all handlers to share information between handlers and routes.

These are methods of the `RouteState` you can use:

- `skip()` - Set the state to allow skip to skip all the remaining handlers of the current route to proceed to the next route.
- `unskip()` - Set the state to disallow skip to cancel the skip state.
- `is_allowed_skip()` - Check if the state is allowed to skip. Values can be `true`, `false`, or `null`. `null` means the state is not set or `skip()` or `unskip()` is not called.
- `next()` - This must be called for each route handler (except the last handler) to proceed to the next handler.
- `stop()` - This should be called if you want want to stop the execution for the next handlers of the current route.
- `is_allowed_next()` - Check if the state is allowed to next. Values can be `true`, `false`, or `null`. `null` means the state is not set or `next()` or `stop()` is not called.
- `extract_info(Route $route)` - Extracts the information from the result of $route-&gt;info() and set it as RouteState properties. Below are the defined route info properties to be extracted:
    - `method` - The HTTP method defined in the route. This also includes the magic methods of this library like ANY, FALLBACK, and STATIC.
    - `path` - The URL path defined in the route. If you set the base path in the router, it will be included in the path.
    - `params` - The URL parameters array defined in the route.
    - `matched` - A boolean value that indicates if the route is matched to the request path.
    - `regex` - The regex pattern used to match the request path to the route path.

Alternatively, you can override the `RouteState` properties by setting it directly like magic. For example:

```
// Override existing properties
$state->method = 'GET';
$state->path = '/user/1';

// Add new properties
$state->user_id = 1;
```

However, there are protected properties that you can't override which are:

- `allow_next`
- `allow_skip`
- `route`

Static Handler `Router::static($path, $directory[, ...$handlers])`
------------------------------------------------------------------

[](#static-handler-routerstaticpath-directory-handlers)

- `$path` - The URL path prefix for the static route.
- `$directory` - The directory path where the request file needs to be looked up.
- `$handlers` - Optional route handlers. These can be any callable function, class static method, or object method call which accepts a `RouterState $state` object as a parameter.

### Serve files from a forbidden directory

[](#serve-files-from-a-forbidden-directory)

Static handler can serve files from a forbidden directory that can't be accessed by the client browser directly because of the web server configuration (e.g. Apache's `deny from all` directive). As long as the system user of the web server application have access to the directory, the static handler can serve the files.

```
$r->static('/', '/');
```

###  Health Score

26

—

LowBetter than 41% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community11

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

Recently: every ~58 days

Total

10

Last Release

956d ago

Major Versions

0.1 → v1.x-dev2023-02-08

0.3.2 → v1.0.02023-11-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/05166f465b8d50e88f58c04319272489cffe23c3b85360244973f973e18c1c0f?d=identicon)[eru123](/maintainers/eru123)

---

Top Contributors

[![eru123](https://avatars.githubusercontent.com/u/39824083?v=4)](https://github.com/eru123 "eru123 (26 commits)")

### Embed Badge

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

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

###  Alternatives

[laravel/dusk

Laravel Dusk provides simple end-to-end testing and browser automation.

1.9k39.6M300](/packages/laravel-dusk)[nineinchnick/edatatables

Grid widget for the Yii Framework, wrapper for the DataTables jQuery plugin

173.2k](/packages/nineinchnick-edatatables)[link-cloud/fast-hyperf

LinkCloud Fast Hyperf

241.2k1](/packages/link-cloud-fast-hyperf)

PHPackages © 2026

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