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

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

marceauka/router
================

Simple PHP Router with no dependencies

2.0.1(5y ago)81153MITPHPPHP &gt;=7.4|&gt;=8.0CI passing

Since Aug 6Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/MarceauKa/Router)[ Packagist](https://packagist.org/packages/marceauka/router)[ RSS](/packages/marceauka-router/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (2)Dependencies (1)Versions (14)Used By (0)

Router
======

[](#router)

[![Build Status](https://camo.githubusercontent.com/ec40a6711c4e0c56ffe8a7c24e209fb193872d6374239e5ec1817e70fd9a787d/68747470733a2f2f7472617669732d63692e6f72672f4d6172636561754b612f526f757465722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/MarceauKa/Router)

Router is a lightweight HTTP resquest router written in PHP.

It will be your perfect companion if you need a simple and effective library or if you want an **easy to understand routing library**.
Otherwise, take a look at these awesome libraries [symfony/routing](https://symfony.com/doc/current/components/routing.html) ou [league/route](http://route.thephpleague.com/).

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

[](#installation)

Router can be installed with composer: `composer require marceauka/router`. For now, it requires PHP 7.4 or 8.0.

Also, copy / paste **src/Router.php** where you want and **require it**.

Configure Apache
----------------

[](#configure-apache)

The router works perfectly with any kind of URL, but if you want some url rewriting, you can use this example .htaccess.

```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

```

Usage
-----

[](#usage)

### Instanciation

[](#instanciation)

Router as no params.

```
$router = new Router;
```

### Adding routes

[](#adding-routes)

Once you have the instance, adding routes is childish.

```
// Will respond to : /hello (en GET)
$router->get('hello', function () {
	echo 'Hello world!';
});
```

Your routes can follow these HTTP verbs: **POST**, **PUT**, **PATCH** and **DELETE**.

```
// POST request
$router->post(...);
// PATCH request
$router->patch(...);
```

A route can use many HTTP verbs:

```
// GET and POST requests
$router->add(['GET', 'POST'], 'hello', ...);
// ... Or all HTTP verbs
$router->any('hello', ...);
```

Finally, routes can be chained or added with a callback:

```
// Chaining
$router->get('foo', ...)->get('bar', ...);
// ...or via a callback
$router->routes(function ($router) {
	// Votre logique
});
```

If no callback is given to the routes() method, all routes will be returned.

```
$router->get('hello', ...);

var_dump($router->routes()); // Returns [1 => ['uri' => 'hello', 'action' => '...']]
```

### Listening requests

[](#listening-requests)

For everything to work, Router needs to incoming requests:

```
// Will use REQUEST_URI and REQUEST_METHOD
$router->listen();
// You can spoof them with your own logic (Request library for example).
$router->listing('request', 'method');
```

### Dispatching actions

[](#dispatching-actions)

Obviously, for each route, a need. You need to define an action for each of them.

- A callback :

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

- A class (controller, ...) :

```
$router->get('hello', 'MyClass@myMethod');
```

Here, the route, once matched, will instanciate the class named "MyClass" and will call the "myMethod" method.
Note: Router will **accepts namespaces** if you application can autoload them (PSR-4, ...).

```
$router->get('route-namespace', 'App\Http\Controller@myMethod');
```

Besides, you can define a global namespace for all of your actions.

```
// Will call App\Http\Controller\Account@resume()
$router->namespaceWith('App\Http\Controller')->get('mon-account', 'Account@resume');
```

You can define a not found action when no routes was matched.

```
$router->whenNotFound(function () {
    echo 'Page not found';
});
```

### URL parameters

[](#url-parameters)

Your routes can contains dynamic parameters. Usage is simple.

```
// Autorise "profile/1" or "profile/12" but not "profile/john".
$router->get('profile/{:num}', ...);
```

Parameters can be:

- {:num} for a numeric value
- {:alpha} for a alpha value
- {:any} for all kinds of chars
- {:slug} for numbers, alpha, dash (-) and arobase (@)

Once matched, parameters are sent to the corresponding action in the URL defined order.

```
$router->get('profile/{:num}/{:alpha}', function ($id, $name) {
	echo "My name is $name and my ID is $id !";
});
```

### Named routes

[](#named-routes)

You can **give a name to your routes** to access them later or easily creating links (in a view for example).

```
$router->get('/homepage', '...', 'home');
$router->link('home'); // Returns "/homepage"
```

If your route contains parameters, you can build an URI with filled parameters.
You need to give all parameters expected by the route, otherwise and exception will be rised.

```
$router->get('/tag/{:slug}', '...', 'tag');
$router->link('tag', 'wordpress'); // => Returns "/tag/wordpress"

$router->get('/user/{:num}/{:any}', '...', 'profile');
$router->link('profile', [42, 'JohnDoe']); // => Returns "/user/42/JohnDoe"
```

### Caching

[](#caching)

Sometimes, when our router contains many routes, it's convenient to have a ready-to-use Router instance for each script execution. Router supports **serialization** and **unserialization**. Two helpers exists to assists you.

- Export the configured instance:

```
$compiled = $router->getCompiled(); // Retourns a string
```

- Import a configured instance:

```
$router = MarceauKa\Router::fromCompiled($compiled); // Returns the instance previously configured
```

Note: **Routes using a callback** can't be serialized. Only the "MyClass@myMethod" is serializable.
The router does not provide functionnality to store or read a cache file. It's not its goal.

Tests
-----

[](#tests)

Tests are with PHPUnit 9. You can use the **phpunit** command given at **vendor/bin**.

```
vendor/bin/phpunit
```

Tests are certainly incomplete. Feel free to contribute.

Licence
-------

[](#licence)

MIT

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance59

Moderate activity, may be stable

Popularity17

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 94.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 ~132 days

Recently: every ~396 days

Total

13

Last Release

1980d ago

Major Versions

0.1.4 → 1.0.02016-08-19

1.0.1 → 2.0.12020-12-15

PHP version history (4 changes)0.0.1PHP 5.4

0.0.2PHP &gt;=5.4

0.0.5PHP &gt;=5.6

2.0.1PHP &gt;=7.4|&gt;=8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1665333?v=4)[Marceau Casals](/maintainers/MarceauKa)[@MarceauKa](https://github.com/MarceauKa)

---

Top Contributors

[![MarceauKa](https://avatars.githubusercontent.com/u/1665333?v=4)](https://github.com/MarceauKa "MarceauKa (36 commits)")[![n-rodriguez](https://avatars.githubusercontent.com/u/3433835?v=4)](https://github.com/n-rodriguez "n-rodriguez (2 commits)")

---

Tags

httprestroutesrouterlibrarySimple

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[contributte/api-router

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

20802.8k3](/packages/contributte-api-router)[aphiria/aphiria

The Aphiria framework

1427.7k2](/packages/aphiria-aphiria)

PHPackages © 2026

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