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

ActiveLibrary[Framework](/categories/framework)

sevens/router
=============

Simple Php High Speed Web Application Router library with PSR-7 Compliance

v1.1.0(5y ago)130MITPHPPHP &gt;=7.4.0CI failing

Since Mar 16Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/temmyscope/router)[ Packagist](https://packagist.org/packages/sevens/router)[ RSS](/packages/sevens-router/feed)WikiDiscussions master Synced 4d ago

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

About SevenRouter
-----------------

[](#about-sevenrouter)

```
=> Seven Router is developed by Elisha Temiloluwa [ TemmyScope ]

=> The Library uses the PHP-DI dependency container to inject dependencies.

=> The Library has been completely unit tested and is ready for use.

=> Updated for PHP 8.4 with strict types, typed properties, and safer cache loading.

```

### Installation

[](#installation)

```
composer require sevens/router
```

### Requirements

[](#requirements)

- PHP 8.4+

### PHP &gt;=8.4 Performance Hack

[](#php-84-performance-hack)

```
=> Use preloader to preload the cached route file after compilation on a production server.

```

### Seven\\Router\\Router: Usage

[](#sevenrouterrouter-usage)

#### Initialize the class

[](#initialize-the-class)

```
use \Seven\Router\Router;

#namespace: refers to the namespace from which the classes should be loaded
$route = new Router($namespace = 'App\Controllers');
```

#### Performance Optimization and Cache

[](#performance-optimization-and-cache)

```
=> To Improve performance on a production server, you should enable cache.

```

***Downside: Whenever a new route is added, You have to delete the cache file from the cache directory in order for the new route to be reloaded.***

```
$route->enableCache($directory = __DIR__.'/cache');
```

```
=> Cache directories are created automatically if missing.

```

#### Registering PSR-7 Compliant/Implementing Request &amp; Response Objects

[](#registering-psr-7-compliantimplementing-request--response-objects)

```
=> This is an optional feature; You don't have to register PSR-7 request & response objects

```

```
/**
* @param $request
* @param $response
*
* @return void
*/
$route->registerProviders($request, $response);
```

#### Register middlewares you want to use later in your route calls:: All Callables are acceptable

[](#register-middlewares-you-want-to-use-later-in-your-route-calls-all-callables-are-acceptable)

\*\*\*Note: registered middlewares only run/load after the associated route is matched/found.
Running middlewares before matching the routes can only be done if you implement it in our application or by extending the router

---

#### The "next" is an object of the PSR-15 RequestHandlerInterface

[](#the-next-is-an-object-of-the-psr-15-requesthandlerinterface)

```
=> This means the handle method is available as well as it can be invoked like a function.

```

***Note: You can only use the "handle" method of the "next" object if you registered $request &amp; $response objects that implement PSR-7 Interface; Else, just call next as a function|closure i.e. next(request, response)***

```
$route->middleware('auth', function($request, $response, RequestHandlerInterface $next){
 #do something with request or set headers for response

 #if required conditions are met do:
 $next->handle($request);
});
```

#### It is best when routes are defined in a different file

[](#it-is-best-when-routes-are-defined-in-a-different-file)

```
=> route definition are included/required/loaded into the current file

=> Note: routes can also be defined in the front controller (i.e. in your index.php);

```

```
require __DIR__.'/routes.php';
```

#### The routing process starts here

[](#the-routing-process-starts-here)

```
=> The "run" method processes routes and calls the appropriate action if the request succeeds.

```

```
$route->run(
 $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'] ?? $_SERVER['PATH_INFO'] ?? '/'
);
```

#### The route difinition in the route file that was required in the front controller e.g. index.php

[](#the-route-difinition-in-the-route-file-that-was-required-in-the-front-controller-eg-indexphp)

```
=> All Standard Http Methods are supported: GET, POST, PUT, OPTIONS, PATCH, HEAD, DELETE;

=> All methods accept a callable as the second parameter

=> All callables are injected with the request & response objects that were previously registered

```

```
$route->get('/post/:id/creator/:name', function($request, $response){

});
```

### Multiple Methods to same Route

[](#multiple-methods-to-same-route)

```
$route->addRoute(['OPTIONS', 'GET'], 'home', [HomeController::class, 'index']);
```

#### To make all requests to a certain endpoint return the same callable, use the "all" method

[](#to-make-all-requests-to-a-certain-endpoint-return-the-same-callable-use-the-all-method)

```
$route->all('/posts', function($request, $response){
  return $response->send(
    "This handles all requests to /posts endpoint, regardless of request method"
  );
});
```

#### All params in uri are accessible through the request params object

[](#all-params-in-uri-are-accessible-through-the-request-params-object)

```
$route->put('/post/:key', function($request, $response){
 return $response->send("This is a request containing key: ". $request->params->key )
});
```

#### The "use" method is used to call registered middlewares before returning the endpoint's callable

[](#the-use-method-is-used-to-call-registered-middlewares-before-returning-the-endpoints-callable)

```
=> The middlewares are called in the order in which they were written/passed

=> The second parameter passed to the "use" method must be a closure that accepts no parameter

```

```
#cors middleware is called first in this case.
$route->use(['middleware' => ['cors', 'auth'],'prefix'=>'api' ], function() use ($route){
 $route->get('/post/:id', function($request, $response){

 });

 # request & response objects are passed as arguments automagically
 $route->post('/post', [ PostController::class, 'create' ]);

});
```

#### Shorthand for Use Keyword

[](#shorthand-for-use-keyword)

```
=> There is a shorthand way to use the "use" method (Of-course it is negligibly slower, if you're performance-anxious)

```

```
$route->use('cors,auth;prefix:api;', function() use ($route){
 $route->get('/post/:id', function($request, $response){

 });

 # request & response objects are passed as arguments automagically
 $route->post('/post', [ PostController::class, 'create' ]);

});

#start with a ';' if no middleware is being used
$route->use(';prefix:api/test;', function() use ($route){

});
```

#### Apache - .HTACCESS

[](#apache---htaccess)

```
=> An example .htaccess directive file fit for this router would look sth like this:

```

```

        Options -MultiViews -Indexes

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond $1 !^(cdn|robots.txt)
    RewriteRule ^(.*)$ index.php/$1 [L]

```

#### NGINX Site Configuration Directive

[](#nginx-site-configuration-directive)

```
=> An example nginx configuration directive fit for this router would look sth like this:

```

```
location / {
    try_files $uri $uri/ /index.php?$query_string;
}
```

#### Example use Case In a real Life Applicatiion

[](#example-use-case-in-a-real-life-applicatiion)

```
use Seven\Router\Router;
use Symfony\Component\HttpFoundation\{Request, Response};
use App\Auth;

/*
|---------------------------------------------------------------------------|
| Register The Auto Loader 																									|
|---------------------------------------------------------------------------|
|
*/
require __DIR__.'/vendor/autoload.php';

$request = Request::createFromGlobals();
$response = new Response();

/**
* @package  SevenPHP
* @author   Elisha Temiloluwa
|-----------------------------------------------------------------|
|	SevenPHP by Elisha Temiloluwa a.k.a TemmyScope                |
|-----------------------------------------------------------------|
*/

$router = new Router('App\Controllers');

//$router->enableCache(__DIR__.'/cache');

$router->registerProviders($request, $response);

$router->middleware('cors', function($request, $response, $next){
 $headers = [
  'Access-Control-Allow-Origin'      => '*',
  'Access-Control-Allow-Methods'     => '*',
  'Access-Control-Allow-Credentials' => 'true',
  'Access-Control-Max-Age'           => '86400',
  'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
 ];
 if ($request->isMethod('OPTIONS')){
 	return $response->send('{"method":"OPTIONS"}', 200, $headers);
 }
 foreach($headers as $key => $value){
  $response->headers->set($key, $value);
 }
 $next($request, $response);
});

$router->middleware('auth', function($request, $response, $next){
 $token = $request->getHeader('Authorization');
 if ( !$token || Auth::isValid($token) ) {
	return $response->send('Unauthorized.', 401);
 }
 $request->userId = Auth::getValuesFromToken($token)->user_id;
 $next->handle($request);
});

require __DIR__.'/routes/web.php';

$router->run(
 $_SERVER['REQUEST_METHOD'],
 $_SERVER['REQUEST_URI'] ?? $_SERVER['PATH_INFO'] ?? '/'
);
```

#### Example use Case of PSR-7 Request-Response Handlers In an Applicatiion making use of Symfony/http-foundation

[](#example-use-case-of-psr-7-request-response-handlers-in-an-applicatiion-making-use-of-symfonyhttp-foundation)

***Note: Not all use of PSR-7 compliants Request &amp; Response handlers are this stressful.
This example is given as it might be the most complicated scenario use case.***

```
use Seven\Router\Router;
use Nyholm\Psr7\Factory\Psr17Factory;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
use Symfony\Component\HttpFoundation\{Request, Response};
use App\Auth;

/*
|---------------------------------------------------------------------------|
| Register The Auto Loader 																									|
|---------------------------------------------------------------------------|
|
*/
require __DIR__.'/vendor/autoload.php';

$psr17Factory = new Psr17Factory();
$psrHttpFactory = new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);

$request = $psrHttpFactory->createRequest(Request::createFromGlobals());

$response = $psrHttpFactory->createResponse(new Response());

/**
* @package  SevenPHP
* @author   Elisha Temiloluwa
|-------------------------------------------------------------------------------|
|	SevenPHP by Elisha Temiloluwa a.k.a TemmyScope 																|
|-------------------------------------------------------------------------------|
*/

$router = new Router('App\Controllers');

$router->registerProviders($request, $response);

$router->middleware('cors', function($request, $response, $next){
 $headers = [
  'Access-Control-Allow-Origin'      => '*',
  'Access-Control-Allow-Methods'     => '*',
  'Access-Control-Allow-Credentials' => 'true',
  'Access-Control-Max-Age'           => '86400',
  'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
 ];
 if ($request->getMethod() === 'OPTIONS'){
  return $response->send('{"method":"OPTIONS"}', 200, $headers);
 }
 foreach($headers as $key => $value){
  $response->withHeader($key, $value);
 }
 $next->handle($request);
});

$router->middleware('auth', function($request, $response, $next){
 $token = $request->getHeader('Authorization');
 if ( !$token || Auth::isValid($token) ) {
	return $response->send('Unauthorized.', 401);
 }
 $request->userId = Auth::getValuesFromToken($token)->user_id;
 $next->handle($request);
});

require __DIR__.'/routes/web.php';

$router->run(
 $_SERVER['REQUEST_METHOD'],
 $_SERVER['REQUEST_URI'] ?? $_SERVER['PATH_INFO'] ?? '/'
);
```

***Note: Routes without parameters are resolved faster than those that accept parameters***

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance53

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

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

Total

4

Last Release

1875d ago

Major Versions

v0.9.3 → v1.0.02020-11-04

PHP version history (2 changes)v0.9.2PHP &gt;=7.1.0

v1.1.0PHP &gt;=7.4.0

### Community

Maintainers

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

---

Top Contributors

[![temmyscope](https://avatars.githubusercontent.com/u/16116067?v=4)](https://github.com/temmyscope "temmyscope (54 commits)")

---

Tags

routersimple-routerrouting-enginefast-router

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[slim/slim

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs

12.2k49.9M1.3k](/packages/slim-slim)[pecee/simple-router

Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.

696214.6k17](/packages/pecee-simple-router)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[yiisoft/router

Yii router

62321.8k21](/packages/yiisoft-router)[developermarius/simple-router

Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.

112.4k](/packages/developermarius-simple-router)

PHPackages © 2026

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