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

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

rudra/router
============

Rudra framework

2024(2y ago)11.0k2MITPHPPHP &gt;=7.4CI passing

Since Jul 30Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/Jagepard/Rudra-Router)[ Packagist](https://packagist.org/packages/rudra/router)[ RSS](/packages/rudra-router/feed)WikiDiscussions master Synced 6d ago

READMEChangelog (7)Dependencies (15)Versions (17)Used By (2)

[![PHPunit](https://github.com/Jagepard/Rudra-Router/actions/workflows/php.yml/badge.svg)](https://github.com/Jagepard/Rudra-Router/actions/workflows/php.yml)[![Maintainability](https://camo.githubusercontent.com/b69c0e568f668d995d54d2541307cfba206549f823832ad00d8f4b7e46e6cd4e/68747470733a2f2f716c74792e73682f6261646765732f64393235323131342d356363342d343035652d626266372d3634313965633530323636662f6d61696e7461696e6162696c6974792e737667)](https://qlty.sh/gh/Jagepard/projects/Rudra-Router)[![CodeFactor](https://camo.githubusercontent.com/a95bde2d37ec74ef06ef7562ee3f40527786ea3d6326146d1465a2927d6165b8/68747470733a2f2f7777772e636f6465666163746f722e696f2f7265706f7369746f72792f6769746875622f6a616765706172642f72756472612d726f757465722f6261646765)](https://www.codefactor.io/repository/github/jagepard/rudra-router)[![Coverage Status](https://camo.githubusercontent.com/53fda88a2824a3d573c61ee35de0631b58e184a264890f986763883bd6516e53/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4a616765706172642f52756472612d526f757465722f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/Jagepard/Rudra-Router?branch=master)

---

Rudra-Router
============

[](#rudra-router)

A lightweight and transparent HTTP router for PHP. Supports dynamic parameters, regular expressions, middleware, and RESTful resources.

Features
--------

[](#features)

- Dynamic URL parameters (`:name`) and regular expressions (`:[\d]{1,3}`)
- All HTTP methods supported: GET, POST, PUT, PATCH, DELETE
- Method spoofing via `_method` (for PUT/PATCH/DELETE from POST requests)
- Middleware executed before and after controller execution
- RESTful resources in a single line
- Automatic dependency injection via IoC container
- Works via instance or Facade

Installation
------------

[](#installation)

```
composer require rudra/router
```

Basic Usage
-----------

[](#basic-usage)

### Initialization

[](#initialization)

```
use Rudra\Router\Router;
use Rudra\Container\Rudra;

$router = new Router(Rudra::run());
```

### Facade Usage

[](#facade-usage)

```
use Rudra\Container\Facades\Rudra;
use Rudra\Router\RouterFacade as Router;
use Rudra\Container\Interfaces\RudraInterface;

Rudra::binding()->set([RudraInterface::class => Rudra::run()]);
```

Route Definition
----------------

[](#route-definition)

### Simple Routes with Closure

[](#simple-routes-with-closure)

```
$router->get('hello/:name', function ($name) {
    echo "Hello $name!";
});
```

### With Regular Expressions

[](#with-regular-expressions)

```
$router->get('user/:[\d]{1,3}', function ($id) {
    echo "User ID: $id";
});
```

### Controller Method Call

[](#controller-method-call)

```
$router->get('read/:id', [MainController::class, 'read']);
```

### Via Facade

[](#via-facade)

```
Router::get('callback/:name', function ($name) {
    echo "Hello $name!";
});

Router::get('read/:id', [MainController::class, 'read']);
```

HTTP Methods
------------

[](#http-methods)

```
$router->get('read/:id',      [MainController::class, 'read']);
$router->post('create/:id',   [MainController::class, 'create']);
$router->put('update/:id',    [MainController::class, 'update']);
$router->patch('patch/:id',   [MainController::class, 'patch']);
$router->delete('delete/:id', [MainController::class, 'delete']);
```

### Any Method (GET|POST|PUT|PATCH|DELETE)

[](#any-method-getpostputpatchdelete)

```
$router->any('any/:id', [MainController::class, 'any']);
```

Middleware
----------

[](#middleware)

Middleware runs before (`before`) and after (`after`) the controller. Each middleware must implement the `__invoke()` method.

### Basic Setup

[](#basic-setup)

```
$router->get('read/page', [MainController::class, 'read'], [
    'before' => [AuthMiddleware::class],
    'after'  => [LogMiddleware::class]
]);
```

### Middleware with Parameters

[](#middleware-with-parameters)

```
$router->get('admin/:id', [AdminController::class, 'show'], [
    'before' => [
        AuthMiddleware::class,
        [RoleMiddleware::class, ['role' => 'admin', new PermissionChecker()]]
    ],
    'after' => [
        LogMiddleware::class,
        [CacheMiddleware::class, ['ttl' => 3600]]
    ]
]);
```

### Middleware Example

[](#middleware-example)

```
use Rudra\Router\RouterFacade as Router;

class AuthMiddleware
{
    public function __invoke($next, ...$params)
    {
        // Logic before controller
        if (!Auth::check()) {
            throw new UnauthorizedException();
        }

        // Pass control to the next middleware in chain
        if ($next) {
            Router::handleMiddleware($next);
        }

        // Logic after controller (optional)
    }
}
```

Simple middleware without chain:

```
class UnsetSessionMiddleware
{
    public function __invoke($next, ...$params)
    {
        Session::remove('value');
        Session::remove('alert');
        Session::remove('errors');

        if ($next) {
            Router::handleMiddleware($next);
        }
    }
}
```

RESTful Resources
-----------------

[](#restful-resources)

Registers standard CRUD routes with explicit plural and singular URL patterns. No magic pluralization — you define exactly what the URLs look like.

```
$router->resource('api/users', 'api/user', UserController::class);
```

This creates the following routes:

MethodURLController MethodDescriptionGETapi/usersindexList all usersGETapi/user/:idreadGet single userPOSTapi/userscreateCreate new userPUTapi/user/:idupdateFull update userPATCHapi/user/:idupdatePartial update userDELETEapi/user/:iddeleteDelete user> The default action names are \[index, read, create, update, delete\].

### Custom Method Names

[](#custom-method-names)

You can override the default action names by passing a custom array of 5 methods:

```
$router->resource('api/posts', 'api/post', PostController::class, [
    'actionIndex',   // GET    api/posts       — list all posts
    'actionView',    // GET    api/post/:id    — get single post
    'actionAdd',     // POST   api/posts       — create new post
    'actionUpdate',  // PUT/PATCH api/post/:id — update post
    'actionDrop'     // DELETE api/post/:id    — delete post
]);
```

> The array order is fixed: \[index, read, create, update, delete\].

The set() Method — Extended Syntax
----------------------------------

[](#the-set-method--extended-syntax)

Allows defining a route with multiple HTTP methods via `|`:

```
$router->set([
    'url'        => '/api/users/:id',
    'method'     => 'GET|POST',
    'controller' => [UserController::class, 'handle'],
    'middleware' => [
        'before' => [AuthMiddleware::class],
        'after'  => [LogMiddleware::class]
    ]
]);
```

Controller Lifecycle
--------------------

[](#controller-lifecycle)

When a controller method is invoked, the following stages are executed:

1. `shipInit()` — base component initialization
2. `containerInit()` — container initialization
3. `init()` — user-defined initialization
4. `before()` — hook before middleware
5. **`before` middleware**
6. **Action method call** (with automatic dependency injection)
7. **`after` middleware**
8. `after()` — hook after middleware

Automatic Dependency Injection
------------------------------

[](#automatic-dependency-injection)

Action method parameters are automatically resolved via the IoC container:

```
class UserController extends Controller
{
    public function show(int $id, Request $request, UserService $service)
    {
        // $id — from URL
        // $request and $service — injected automatically
    }
}
```

Method Spoofing
---------------

[](#method-spoofing)

For forms that do not support PUT/PATCH/DELETE, use the `_method` parameter:

```

```

The router automatically recognizes this as a PUT request.

Error Handling
--------------

[](#error-handling)

- `RouterException("Not Found", 404)` — route not found or parameters do not match
- `RouterException("Service Unavailable", 503)` — controller method does not exist
- `MiddlewareException` — error in the middleware chain

License
-------

[](#license)

This project is licensed under the **Mozilla Public License 2.0 (MPL-2.0)** — a free, open-source license that:

- Requires preservation of copyright and license notices,
- Allows commercial and non-commercial use,
- Requires that any modifications to the original files remain open under MPL-2.0,
- Permits combining with proprietary code in larger works.

📄 Full license text: [LICENSE](./LICENSE)
🌐 Official MPL-2.0 page:

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance56

Moderate activity, may be stable

Popularity20

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 99.7% 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 ~208 days

Recently: every ~4 days

Total

15

Last Release

26d ago

Major Versions

v2.0.0 → v25.102025-06-26

v25.6 → v26.52026-05-21

PHP version history (4 changes)v2.0.0PHP &gt;=7.1

v2020PHP &gt;=7.4

v25.10PHP &gt;=8.3

v26.7PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/75e65761bdd94035d1c783773a706d5722ce3164fe55d9722581c2cb4a642d8c?d=identicon)[jagepard](/maintainers/jagepard)

---

Top Contributors

[![Jagepard](https://avatars.githubusercontent.com/u/4591345?v=4)](https://github.com/Jagepard "Jagepard (602 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (2 commits)")

---

Tags

middlewarerestrest-routerrestfulrouterroutingrudrarestrouterroutingREST routerrestfulrudra

### Embed Badge

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

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

###  Alternatives

[aplus/routing

Aplus Framework Routing Library

2581.6M3](/packages/aplus-routing)[contributte/api-router

RESTful Router for your Apis in Nette Framework - created either directly or via attributes

20814.8k4](/packages/contributte-api-router)

PHPackages © 2026

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