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

ActiveLibrary[Framework](/categories/framework)

webiny/router
=============

Webiny Router Component

v1.6.1(8y ago)2842MITPHPPHP ^7

Since Sep 20Pushed 8y ago11 watchersCompare

[ Source](https://github.com/Webiny/Router)[ Packagist](https://packagist.org/packages/webiny/router)[ Docs](http://www.webiny.com/)[ RSS](/packages/webiny-router/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (1)Dependencies (7)Versions (23)Used By (2)

Router Component
================

[](#router-component)

Router component is used for mapping defined paths/urls to appropriate controllers or services.

Install the component
---------------------

[](#install-the-component)

The best way to install the component is using Composer.

```
composer require webiny/router
```

For additional versions of the package, visit the [Packagist page](https://packagist.org/packages/webiny/router).

Usage
-----

[](#usage)

Defining a route is a rather easy process, you set a route name and underneath you define the path and the callback. Here is an example:

```
    Router:
        Routes:
            BlogTag:
                Path: blog/tag/{tag}
                Callback: MyApp\Blog\showTag
            BlogComments:
                Path: blog/post/{id}/comments
                Callback:
                    Class: MyApp\Blog
                    Method: showComments
            BlogPost:
                Path: blog/post/{slug}/{id}
                Callback: MyApp\Blog\showPost
                Options:
                    slug:
                        Pattern: .*?
            BlogAuthor:
                Path: blog/authors/{author}
                Callback: MyApp\Blog\showAuthorPosts
                Options:
                    author:
                        Default: webiny
            Blog:
                Path: blog
                Callback: MyApp\Blog\index
```

If a route is matched you will get an instance of `MatchedRoute`. The `getCallback` method returns the value of callback parameter of the matched route. The second method `getParams` returns the values of the parameters defined in the `Path` section.

By registering a default `Router` configuration, `Router` will automatically set the defined routes and cache driver.

```
    Router::setConfig($pathToYourConfig);
```

Later on you can use the `RouterTrait` access that `Router` instance.

**NOTICE:**When defining the routes in your config file, make sure that you put routes with lesser precision to the bottom, and routes with a more stricter rules at the top. A common pitfall is that a route with more wider pattern is matched before a route with a more stricter rules due to the fact that the `Router` loops over the defined routes in the same order that they are defined inside the config file, and it stops once the first route is matched.

### `Options`

[](#options)

The `Options` attribute under the route provides you two additional options that you can set under each route.

#### `Pattern`

[](#pattern)

The default regex pattern for matching a variable is `{[\w-]+}`. Using the `Pattern` attribute you can set your own rule.

#### `Default`

[](#default)

The `Default` attribute gives you the option to set the the default value for a variable.

If the route is not matched using the current available properties from the url path, `Router` will replace all the variable patterns with the default values and try to match the route again.

Matching routes
---------------

[](#matching-routes)

To check if a route matches the given path, use the `RouterTrait` and then just call `$this->router()->match()` method. The `match` method takes either a string that is representing a url or it can take an instance of `Url` standard object. If the router successfully matches one of the routes it will return an array with callback and params attributes. If the router doesn't match any of the routes, it will return false.

```
class MyClass
{
	use \Webiny\Component\Router\RouterTrait;

	function __construct(){
		$result = $this->router()->match('blog/tag/some_tag');
		$result = $this->router()->match('http://www.webiny.com/blog/post/some-post/12');
	}
}
```

**NOTE:** `Router` component always returns the **first route** that matches the given path.

Executing route callback
------------------------

[](#executing-route-callback)

If you define your callback as string, you will have to parse and execute it on your own. But if you follow the standard structure of your callback you will be able to use router's `execute` method and pass your `MatchedRoute` to it. Router will then execute the callback for you and do all the checks regarding class and method existence:

```
BlogComments:
    Path: blog/post/{id}/comments
    Callback:
        Class: MyApp\Blog
        Method: showComments
```

```
class MyClass
{
	use \Webiny\Component\Router\RouterTrait;

	function __construct(){
		$result = $this->router()->match('blog/post/12/comments');
		if($result){
		    $callbackResult = $this->router()->execute($result);
		}
	}
}
```

If for some reason you need to call the method statically, define your route callback like this:

```
BlogComments:
    Path: blog/post/{id}/comments
    Callback:
        Class: MyApp\Blog
        Method: showComments
        Static: true
```

Generating routes
-----------------

[](#generating-routes)

With the `Router` your don't have write the urls inside your code or views, instead you can generate the urls from the given route like this:

```
class MyClass
{
	use \Webiny\Component\Router\RouterTrait;

	function __construct(){
		$url = $this->router()->generate('BlogTag',  ['tag'=>'html5', 'page'=>1]);
		// http://www.webiny.com/blog/tag/html5/?page=1
		// page was not defined in the route, that's why it's appended as a query param

		$url = $this->router()->generate('BlogAuthor');
		// http://www.webiny.com/blog/authors/webiny
		// the value of "author" was not set, so the generator used the default value
	}
}
```

You see that `Router` replaced the `{tag}` parameter with the provided value, in this case it was `html5`. You can also notice that the `page` parameter isn't defined in our route, so the `Router` appended that parameter as a query string.

Configuration
-------------

[](#configuration)

The `Router` component takes one additional configuration parameter, and that is the `Cache` parameter. If either defines the name of the cache service that will be used to cache some of the internal mechanisms, or you can set it to `false` if you don't want the component to use cache.

```
Router:
    Cache: TestCache
```

Using the cache can speed up matching of routes, especially more complex ones.

Resources
---------

[](#resources)

To run unit tests, you need to use the following command:

```
$ cd path/to/Webiny/Component/Router/
$ composer.phar install
$ phpunit

```

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity73

Established project with proven stability

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

Recently: every ~5 days

Total

22

Last Release

3153d ago

PHP version history (3 changes)1.0.x-devPHP &gt;=5.4.0

1.2.x-devPHP &gt;=5.5.9

1.5.x-devPHP ^7

### Community

Maintainers

![](https://www.gravatar.com/avatar/4440afa738ed146b05c06073a90345e0464c4f4d042b039532d881ca24859d77?d=identicon)[SvenAlHamad](/maintainers/SvenAlHamad)

---

Top Contributors

[![SvenAlHamad](https://avatars.githubusercontent.com/u/3808420?v=4)](https://github.com/SvenAlHamad "SvenAlHamad (17 commits)")

---

Tags

routerrouting

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[klein/klein

A lightning fast router for PHP

2.7k1.1M31](/packages/klein-klein)[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)[vlucas/bulletphp

A heierarchical resource-oriented micro-framework built on nested closures instead of route-based callbacks

41949.9k1](/packages/vlucas-bulletphp)[izniburak/router

simple router class for php

23522.6k7](/packages/izniburak-router)[vectorface/snappy-router

A quick and snappy routing framework.

4614.7k](/packages/vectorface-snappy-router)[thewunder/croute

Convention based routing for PHP

1317.4k](/packages/thewunder-croute)

PHPackages © 2026

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