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

ActiveLibrary[Framework](/categories/framework)

jdz/router
==========

JDZ Router is a PHP routing library built on top of the Symfony Routing component.

2.0.0(5mo ago)016MITPHPPHP &gt;=8.2

Since May 14Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/joffreydemetz/router)[ Packagist](https://packagist.org/packages/jdz/router)[ Docs](https://jdz.joffreydemetz.com/router/)[ RSS](/packages/jdz-router/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (6)Versions (11)Used By (0)

JDZ Router
==========

[](#jdz-router)

`Router` is a PHP routing library built on top of the **Symfony Routing** component. It provides a clean and intuitive API for managing routes, generating URLs, and handling HTTP requests in your web applications.

Features
--------

[](#features)

- Built on the **Symfony Routing** component for robust routing capabilities.
- Generate routes programmatically and export to YAML format.
- Load routes from YAML files with support for multiple file sources.
- Route matching with automatic request parameter parsing.
- URL generation for named routes (relative and absolute).
- Redirect path management for legacy URL handling.
- Support for JSON endpoints with automatic format detection.
- HTTP method constraints (GET, POST, etc.).
- Route parameter requirements and defaults.
- Immutable route collections for read-only configurations.
- Type-safe with PHP 8.2+ features.

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

[](#installation)

Add the package to your project using **Composer**:

```
composer require jdz/router
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- symfony/config
- symfony/http-foundation
- symfony/routing
- symfony/string
- symfony/yaml (for YAML support)

Usage
-----

[](#usage)

For a complete example, check the `examples` folder in the repository.

### Basic Router Setup

[](#basic-router-setup)

```
use JDZ\Router\Router;
use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();
$router = new Router(__DIR__ . '/routes/', $request);

// Load routes from YAML files
$router->addYml('routes.yml');
$router->addYml('api-routes.yml');
```

### Generating Routes

[](#generating-routes)

```
use JDZ\Router\Generator\Routes;
use JDZ\Router\Generator\Route;

$routes = new Routes();

// Add routes using Route objects
$routes->addRoutes([
    new Route('/home/', 'Home', [
        'component' => 'main',
        'task' => 'home',
    ]),

    new Route('/search/', 'Search', [
        'component' => 'search',
        'task' => 'display',
    ]),
]);

// Add route using array notation
$routes->addRoutes([
    [
        'url' => '/contact/',
        'name' => 'Contact',
        'vars' => [
            'component' => 'contact',
            'task' => 'form',
        ],
    ],
]);

// Create and add a route
$route = $routes->createRoute('/about/', 'About', [
    'component' => 'page',
    'task' => 'display',
    'slug' => 'about',
]);
$routes->addRoute($route);
```

### Export Routes to YAML

[](#export-routes-to-yaml)

```
use Symfony\Component\Yaml\Yaml;

// Export routes to array format
$routesArray = $routes->export();

// Write to YAML file
$yamlContent = Yaml::dump($routesArray, 4, 2);
file_put_contents('routes.yml', $yamlContent);
```

Example YAML output:

```
home:
    path: /home/
    defaults:
        component: main
        task: home
    methods: [GET]

search:
    path: /search/
    defaults:
        component: search
        task: display
    methods: [GET]
```

### Route Matching

[](#route-matching)

```
// Match the current request
$match = $router->match();

if ($match !== false) {
    $component = $match['component'];
    $task = $match['task'];
    // Handle the matched route
}

// Match a specific path
$match = $router->match('/search/');
```

### URL Generation

[](#url-generation)

```
// Generate URL for a named route
$url = $router->url('search');
// Returns: /search/

// Generate URL with parameters
$url = $router->url('userProfile', ['id' => 123]);
// Returns: /user/123/

// Generate absolute URL
$absoluteUrl = $router->url('search', [], true);
// Returns: https://example.com/search/
```

### Loading Routes into Application

[](#loading-routes-into-application)

```
use JDZ\Router\Route;

$route = new Route($router, $request);

try {
    $route->load();

    // Check if it's a JSON endpoint
    if ($route->isJson()) {
        header('Content-Type: application/json');
    }

    // Access parsed parameters
    $component = $request->query->get('component');
    $task = $request->query->get('task');

} catch (\JDZ\Router\RouterException $e) {
    // Handle route not found
    http_response_code(404);
    echo 'Page not found';
}
```

### Redirect Management

[](#redirect-management)

```
// Add redirect paths for legacy URLs
$router->addRedirectPaths([
    '/old-path/' => '/new-path/',
    '/legacy/page/' => '/page/',
]);
```

### JSON Routes

[](#json-routes)

```
// Routes with JSON format
$route = new Route('/json/api/', 'ApiEndpoint', [
    'component' => 'api',
    'task' => 'getData',
], true); // true indicates JSON format

// In YAML:
# jsonApi:
#     path: /json/api/
#     defaults:
#         _format: json
#         component: api
#         task: getData
#     requirements:
#         _format: json
```

### HTTP Method Constraints

[](#http-method-constraints)

```
$route = new Route('/form/', 'ContactForm', [
    'component' => 'contact',
    'task' => 'form',
]);
$route->setMethods(['GET', 'POST']);
```

### Route Options

[](#route-options)

```
$route = new Route('/vault/', 'Vault', [
    'component' => 'secure',
]);
$route->setOption('ignoreLastUrl', true);
```

### Immutable Routes

[](#immutable-routes)

```
use JDZ\Router\Generator\RoutesImmutable;

// Create immutable route collection
$immutableRoutes = new RoutesImmutable([
    new Route('/home/', 'Home'),
    new Route('/about/', 'About'),
]);

// Add new routes (allowed)
$immutableRoutes->addRoute(new Route('/contact/', 'Contact'));

// Try to modify existing route (throws exception)
try {
    $immutableRoutes->addRoute(new Route('/home/', 'HomeModified'));
} catch (\Exception $e) {
    // Routes are immutable
}
```

Testing
-------

[](#testing)

The package includes a comprehensive test suite with 100 tests covering all functionality.

To run the tests:

```
composer test
```

Or directly with PHPUnit:

```
vendor/bin/phpunit --colors=always --testdox
```

License
-------

[](#license)

This project is licensed under the MIT License - see the LICENSE file for details.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance81

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity56

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

Recently: every ~52 days

Total

9

Last Release

159d ago

Major Versions

1.0.13 → 2.0.02025-12-11

### Community

Maintainers

![](https://www.gravatar.com/avatar/5e83e3701566e43438525ed14578487e732b849d152b5071aa1613a0dad96913?d=identicon)[jdz](/maintainers/jdz)

---

Top Contributors

[![joffreydemetz](https://avatars.githubusercontent.com/u/15113527?v=4)](https://github.com/joffreydemetz "joffreydemetz (23 commits)")

---

Tags

routerJDZ

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[symfony/framework-bundle

Provides a tight integration between Symfony components and the Symfony full-stack framework

3.6k235.4M9.7k](/packages/symfony-framework-bundle)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)

PHPackages © 2026

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