PHPackages                             bright-webb/easy-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. bright-webb/easy-router

ActiveLibrary

bright-webb/easy-router
=======================

Easy Router is a lightweight PHP routing library designed to simplify url management and request handling for web applications

v1.0.6(1y ago)015MITPHPPHP &gt;=7.4

Since Oct 19Pushed 1y ago1 watchersCompare

[ Source](https://github.com/bright-webb/EasyRouter)[ Packagist](https://packagist.org/packages/bright-webb/easy-router)[ RSS](/packages/bright-webb-easy-router/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (8)Used By (0)

EasyRouter
==========

[](#easyrouter)

Easy Router is a lightweight PHP library designed to simplify routing in web applications. It provides a simple and intuitive way to define routes and handle requests, making it easy to build scalable and maintainable web applications.

Features
--------

[](#features)

- **Route Management**: Supports multiple HTTP methods (GET, POST, PUT, DELETE, PATCH) and route grouping.
- **Middleware Support**: Global and route specific middleware for flexible request handling.
- **View Rendering**: Simple and efficient templating with support for passing dynamic data.
- **Session Utilities**: Built in helper and flash messaging system for better user feedback.
- **Error Handling**: Customizable error handlers for different HTTP status codes.
- **Lightweight**: Minimal dependencies with a focus on performance.

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

[](#installation)

To use Easy Router in your project, you can install it via Composer:

```
composer composer require bright-webb/easy-router
```

Alternatively, download the source files and include them manually in your project.

Getting Started
---------------

[](#getting-started)

### Setup Autoloading

[](#setup-autoloading)

Ensure your project supports PSR-4 autoloading or include the files manually. If using Composer, include the autoloader:

```
require_once __DIR__ . '/vendor/autoload.php';
```

Components
----------

[](#components)

### Router

[](#router)

The `Router` class handles defining and executing routes.

### View

[](#view)

The `View` class simplifies rendering templates

- **`render($view, $data = [])`**: Renders the specified view with optional data.

```
View::render('about', ['company' => 'EasyRouter.']);
```

### Helper

[](#helper)

Utility methods for simplifying common tasks, such as URL generation or string manipulation.

### Flash

[](#flash)

The `Flash` class provides a simple interface for temporary session messages:

- **`set($key, $message)`**: Sets a flash message.
- **`get($key)`**: Retrieves and clears a flash message.

### Error Handling

[](#error-handling)

Custom error handlers for HTTP status codes can be defined:

```
$router->setErrorHandler(404, function() {
    echo 'Page not found.';
});
```

Router Class
------------

[](#router-class)

The `Router` class is the core of the Easy Router library. It manages route definitions, middleware, and request handling.

### Features

[](#features-1)

- Supports multiple HTTP methods (`GET`, `POST`, `PUT`, `DELETE`, `PATCH`).
- Named routes with URL generation.
- Middleware support for both global and route specific middleware.
- Route grouping with prefixes and middleware.
- Customizable error handling for HTTP status codes.
- Event hooks for pre and post route matching.

### Usage Example

[](#usage-example)

#### Basic Routing

[](#basic-routing)

```
use EasyRouter\Router;

$router = Router::getInstance();

// Define routes
$router->get('/', function() {
    echo 'Welcome to Easy Router!';
});

$router->post('/submit', function() {
    echo 'Form submitted!';
});

$router->run();
```

#### Route with Parameters

[](#route-with-parameters)

```
$router->get('/user/{id}', function($id) {
    echo "User ID: $id";
});
```

#### Named Routes

[](#named-routes)

```
$router->get('/profile/{username}', function($username) {
    echo "Profile of $username";
})->name('profile');

// Generate URL
$url = $router->url('profile', ['username' => 'bright']);
echo $url; // Output: /profile/bright
```

#### Grouped Routes

[](#grouped-routes)

```
$router->group(['prefix' => 'admin', 'middleware' => ['auth']], function($router) {
    $router->get('/dashboard', function() {
        echo 'Admin Dashboard';
    });
});
```

You can use a method in place of the callback function if only the method name is provided.

### Example

[](#example)

```
$router->get('/user/{id}',[ UserController::class, 'getUser']);
```

---

### Methods

[](#methods)

#### Constructor and Singleton

[](#constructor-and-singleton)

```
public static function getInstance(): Router
```

Creates and returns a singleton instance of the Router class.

---

#### Adding Routes

[](#adding-routes)

- **`get($path, $callback)`**: Defines a route for `GET` requests.
- **`post($path, $callback)`**: Defines a route for `POST` requests.
- **`put($path, $callback)`**: Defines a route for `PUT` requests.
- **`delete($path, $callback)`**: Defines a route for `DELETE` requests.
- **`patch($path, $callback)`**: Defines a route for `PATCH` requests.
- **`any($path, $callback)`**: Accepts all HTTP methods for a route.
- **`add($method, $path, $callback)`**: Adds a route for a specific HTTP method.

##### Example:

[](#example-1)

```
$router->get('/example', function() {
    echo 'Example route';
});
```

---

#### Middleware

[](#middleware)

- **`middleware($middleware, $callback = null)`**: Attaches middleware to a route or globally.
- **`use(...$args)`**: Adds global middleware, route prefixes, or event hooks.

##### Example

[](#example-2)

```
$router->middleware('auth', function() {
    echo 'Authentication required!';
});
```

---

#### Route Groups

[](#route-groups)

- **`group(array $attributes, callable $callback)`**: Groups routes with shared attributes like prefixes or middleware.

##### Example

[](#example-3)

```
$router->group(['prefix' => 'api', 'middleware' => ['api_auth']], function($router) {
    $router->get('/users', function() {
        echo 'API Users';
    });
});
```

---

#### Named Routes and URL Generation

[](#named-routes-and-url-generation)

- **`name($name)`**: Names a route.
- **`url($name, $parameters = [])`**: Generates a URL for a named route.

##### Example

[](#example-4)

```
$router->get('/home', function() {
    echo 'Home Page';
})->name('home');

echo $router->url('home');
```

---

#### Error Handling

[](#error-handling-1)

- **`error($code, callable $handler)`**: Registers a custom handler for an HTTP error code.

##### Example

[](#example-5)

```
$router->error(404, function() {
    echo 'Page not found!';
});
```

---

#### Running the Router

[](#running-the-router)

- **`run()`**: Starts the router and handles the incoming request.

##### Example:

[](#example-6)

```
$router->run();
```

---

### Advanced Features

[](#advanced-features)

#### Pattern Matching

[](#pattern-matching)

- **`pattern($name, $pattern)`**: Defines custom patterns for route parameters.

##### Example:

[](#example-7)

```
$router->pattern('id', '[0-9]+');
$router->get('/product/{id}', function($id) {
    echo "Product ID: $id";
});
```

#### Event Hooks

[](#event-hooks)

- **`triggerEvent($event, $params = [])`**: Attaches hooks for `before` or `after` route matching.

##### Example:

[](#example-8)

```
$router->use('before', function() {
    echo 'Before route matching';
});
```

---

#### Middleware Redirection

[](#middleware-redirection)

- **`middlewareRedirect($redirectTo)`**: Sets a redirection path for unauthorized access.

##### Example:

[](#example-9)

```
$router->middlewareRedirect('/login');
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please fork the repository and submit a pull request with your changes.

License
-------

[](#license)

Easy Router is open-source software licensed under the [MIT License](LICENSE).

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance39

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity44

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

Total

7

Last Release

521d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f5958d0c8d4903a43f50c3b1b0d3ce01fe71652ba5af72c20b4902afb870fc26?d=identicon)[bright-webb](/maintainers/bright-webb)

---

Top Contributors

[![bright-webb](https://avatars.githubusercontent.com/u/60761289?v=4)](https://github.com/bright-webb "bright-webb (13 commits)")

### Embed Badge

![Health badge](/badges/bright-webb-easy-router/health.svg)

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

###  Alternatives

[elgg/elgg

Elgg is an award-winning social networking engine, delivering the building blocks that enable businesses, schools, universities and associations to create their own fully-featured social networks and applications.

1.7k15.7k5](/packages/elgg-elgg)[api-platform/metadata

API Resource-oriented metadata attributes and factories

243.5M96](/packages/api-platform-metadata)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[flowwow/cloudpayments-php-client

cloudpayments api client

2188.2k](/packages/flowwow-cloudpayments-php-client)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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