PHPackages                             romeoz/rock-route - 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. romeoz/rock-route

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

romeoz/rock-route
=================

Simple router for PHP

0.11.0(10y ago)111MITPHPPHP &gt;=5.4.0

Since Oct 18Pushed 10y ago1 watchersCompare

[ Source](https://github.com/romeOz/rock-route)[ Packagist](https://packagist.org/packages/romeoz/rock-route)[ RSS](/packages/romeoz-rock-route/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (9)Versions (3)Used By (0)

Simple router for PHP
=====================

[](#simple-router-for-php)

[![Latest Stable Version](https://camo.githubusercontent.com/948f15ea4de90a6e07bd6ef4ff5065868b3f36a369a94fb3c92b3c74bb638eaf/68747470733a2f2f706f7365722e707567782e6f72672f726f6d654f7a2f726f636b2d726f7574652f762f737461626c652e737667)](https://packagist.org/packages/romeOz/rock-route)[![Total Downloads](https://camo.githubusercontent.com/b074c22130e710dfa6f31ba2f2fb3ab8b5a16cdaf8610a9d44a753975d71a9a3/68747470733a2f2f706f7365722e707567782e6f72672f726f6d654f7a2f726f636b2d726f7574652f646f776e6c6f6164732e737667)](https://packagist.org/packages/romeOz/rock-route)[![Build Status](https://camo.githubusercontent.com/566bde6468e2ca80685f5ea1557ea2b1f44500ee80d4f4a330d95161dd86bc71/68747470733a2f2f7472617669732d63692e6f72672f726f6d654f7a2f726f636b2d726f7574652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/romeOz/rock-route)[![HHVM Status](https://camo.githubusercontent.com/62d20994c3c80da467c40079924b1607ac9535735c6fcc029ec75caaf407741e/687474703a2f2f6868766d2e683463632e64652f62616467652f726f6d656f7a2f726f636b2d726f7574652e737667)](http://hhvm.h4cc.de/package/romeoz/rock-route)[![Coverage Status](https://camo.githubusercontent.com/75820bf6acaccae6286811bfd0c9b2e611be95c52eb75fed105868685c2d4778/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f726f6d654f7a2f726f636b2d726f7574652f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/r/romeOz/rock-route?branch=master)[![License](https://camo.githubusercontent.com/a8ecc771c20eda37a9edafaf9ff4e833df5e5e0fdcbbf5fd53f4ca61c3ce69f0/68747470733a2f2f706f7365722e707567782e6f72672f726f6d654f7a2f726f636b2d726f7574652f6c6963656e73652e737667)](https://packagist.org/packages/romeOz/rock-route)

Features
--------

[](#features)

- Filters
- Support REST
- Groups
- Inject arguments to action
- Caching rules
- Standalone module/component for [Rock Framework](https://github.com/romeOz/rock)

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Pattern](#pattern)
- [Configurable](#configurable)
- [Filters](#filters)
    - [Custom filter](#custom-filter-as-callable)
- [REST](#rest)
- [Using groups](#using-groups)
    - [Route prefixing](#route-prefixing)
    - [Sub-Domain routing](#sub-domain-routing)
- [Alias for route](#alias-for-route)
- [Using response](#using-response)
- [Inject arguments](#inject-arguments)
- [HMVC](#hmvc-hierarchical-modelviewcontroller)
    - [Local](#local)
    - [Remote](#remote)
- [Caching rules](#caching-rules)
- [Requirements](#requirements)

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

[](#installation)

From the Command Line:

```
composer require romeoz/rock-route

```

or in your composer.json:

```
{
    "require": {
        "romeoz/rock-route": "*"
    }
}
```

Quick Start
-----------

[](#quick-start)

```
// url: http://site.com/items/7/

$route = new Route();

$handler = function(Route $route){
    return 'id: ' . $route->getParam('id');
};

$route->get('/items/{id:\d+}/', $handler, ['as' => 'item']);
$route->post('/items/', ['\namespace\SomeController', 'actionCreate']);
$route->run();

// output: 'id: 7'

echo Alias::getAlias('@item', ['id' => 15]);

// output: '/items/15/'
```

Pattern
-------

[](#pattern)

You can use string or array as pattern.

```
$pattern = [
    Route::FILTER_HOST => '{sub:[a-z]+}.site.com',
    Route::FILTER_PATH => '/items/{id:\d+}/',
    Route::FILTER_GET => [
        'query' => true,
        'view' => 'all',
        'order' => 'sort-{order:(asc|desc)}'
    ]
]
$route->post($pattern, $handler);
```

`'query' => true` indicates that the URL-param `query` was mandatory.

> Pattern as string `/items/{id:\d+}/` is equivalent to `[ Route::FILTER_PATH => '/items/{id:\d+}/' ]`.

Configurable
------------

[](#configurable)

Set a rules you can as configurable. Can be useful for using inside your framework.

```
$config = [
    'rules' => [
        'item' => [Route::GET, '/items/{id:\d+}/', $handler]
    ]
]

$route = new Route($config);
$route->run();
```

For [groups](#using-groups):

```
$config = [
    'groups' => [
        'api' => [
            [Route::GET, Route::POST],
            [ Route::FILTER_HOST => 'api.site.com' ],
            'rules' => [
                'item' => [Route::GET, '/items/{id:\d+}/', $handler]
            ]
        ]
    ]
]

$route = new Route($config);
$route->run();
```

Filters
-------

[](#filters)

For using filters you must be installed [Rock Filters](https://github.com/romeOz/rock-filters): `composer require romeoz/rock-filters`.

An example of disallow by IP (uses `$_SERVER['REMOTE_ADDR']`):

```
$route = new Route();

$handler = function(){
    return 'Hello world!';
};

$filters = [
    'access' => [
        'class' => '\rock\route\filters\AccessFilter',
        'rules' => [
            'allow' => true,
            'ips' => ['10.1.2.3']
        ]
    ]
]

$route->get('/items/{id:\d+}/', $handler, ['filters' => $filters]);
$route->run();
```

\####Custom filter (as callable)

```
$filters = function(Route $route){
    return $route->request->isAjax();
};
```

Must returns true/false (boolean).

REST
----

[](#rest)

```
$route = new Route();

$route->REST('items', 'ItemsController');
$route->run();

class ItemsController
{
    // GET /items/
    public function actionIndex()
    {
        return 'index';
    }

    // GET /items/7/
    public function actionShow()
    {
        return 'show';
    }

    // POST /items/
    public function actionCreate()
    {
        return 'create';
    }

    // PUT /items/7/
    public function actionUpdate()
    {
        return 'update';
    }

    // DELETE /items/7/
    public function actionDelete()
    {
        return 'delete';
    }
}
```

You can specify what actions to use (`only` or `exclude`):

```
$route->REST('items', 'ItemsController', ['only' => ['show', 'create']]);
```

Also you can specify custom REST scenario:

```
$config = [
    'RESTHandlers' => [
            'all' => [
                Route::GET,
                '/{url}/',
                ['{controller}', 'actionAll']
            ],
            'one' => [
                Route::GET,
                '/{url}/{id}/',
                ['{controller}', 'actionOne']
            ],
            'create' => [
                [Route::POST, Route::OPTIONS],
                '/{url}/',
                ['{controller}', 'actionCreate']
            ],
            'update' => [
                [Route::PUT, Route::PATCH, Route::OPTIONS],
                '/{url}/{id}/',
                ['{controller}', 'actionUpdate']
            ],
            'delete' => [
                [Route::DELETE, Route::OPTIONS],
                '/{url}/{id}/',
                ['{controller}', 'actionDelete']
            ]
    ]
];

$route = new Route($config);
```

Using groups
------------

[](#using-groups)

\####Route prefixing

```
// url: http://site.com/api/items/7/

$route = new Route();

$handler = function(Route $route) {
    $handler = function(Route $route){
        return 'id: ' . $route['id'];
    };
    $route->get('/items/{id:\d+}/', $handler, ['as' => 'item']);
    return $route;
};

$route->group(Route::ANY, '/api/{url:.+}', $handler, ['path' => '/api/', 'as' => 'api']);
$route->run();

// output: 'id: 7'

echo Alias::getAlias('@api.item', ['id' => 15]);

// output: '/api/items/15/'
```

Here, the `'path' => '/api/'` is the prefix for the rules of this group.

\####Sub-Domain routing

```
// url: http://api.site.com/items/7/

$route = new Route();

$handler = function(Route $route) {
    $handler = function(Route $route){
        return 'id: ' . $route['id'];
    };
    $route->get('/items/{id:\d+}/', $handler, ['as' => 'item']);
    return $route;
};

$route->group(Route::ANY, [ Route::FILTER_HOST => 'api.site.com' ], $handler, ['as' => 'api']);
$route->run();

// output: 'id: 7'

echo Alias::getAlias('@api.item', ['id' => 15]);

// output: 'api.site.com/items/15/'
```

Alias for route
---------------

[](#alias-for-route)

Using the `as` index of our route array you can assign a alias to a route:

```
$route->get('/items/{id:\d+}/', $handler, ['as' => 'item']);

echo Alias::getAlias('@item', ['id' => 15]);

// output: '/items/15/'
```

Extended example:

```
$pattern = [
    Route::FILTER_HOST => '{sub:[a-z]+}.site.com',
    Route::FILTER_PATH => '/items/{id:\d+}/',
    Route::FILTER_GET => [
        'query' => true,
        'view' => 'all',
        'order' => 'sort-{order:(asc|desc)}'
    ]
]
$route->get($pattern, $handler, ['as' => 'item']);

echo Alias::getAlias('@item');

// output: {sub}.site.com/items/{id}/?view=all&order=sort-{order}
```

Also you can set a alias to [group](#using-groups):

```
$route->group(
    Route::ANY,
    [ Route::FILTER_HOST => 'api.site.com' ],
    $handler, ['as' => 'api']
);
```

All rules belonging to this group will inherit this alias.

For configurable approach you can use the index:

```
$config = [
    'rules' => [
        'item' => [Route::GET, '/items/{id:\d+}/', $handler]
    ]
]

$route = new Route($config);

echo Alias::getAlias('@item');

// output: '/items/{id}/'
```

Using response
--------------

[](#using-response)

For using response you must be installed [Rock Response](https://github.com/romeOz/rock-response): `composer require romeoz/rock-response`.

```
$response = new \rock\response\Response;
$route = new Route(['response' => $response]);

$handler = function(Route $route){
    $route->response->format = \rock\response\Response::FORMAT_JSON;
    return ['id' => $route->getParam('id')];
};

$route->get('/items/{id:\d+}/', $handler, ['as' => 'item']);
$route->run();
$response->send();

// output: {"id":7}
```

More details [see docs](https://github.com/romeOz/rock-response)

Inject arguments
----------------

[](#inject-arguments)

```
$route = new Route;

$route->get('/', ['ItemsController', 'actionIndex'])
$route->run();

class ItemsController
{
    public function actionIndex(\rock\request\Request $request)
    {
        return $request::className();
    }
}

// output: 'rock\request\Request'
```

More flexible use is possible using the library [Rock DI](https://github.com/romeOz/rock-di): `composer require romeoz/rock-di`.

[HMVC (Hierarchical model–view–controller)](https://en.wikipedia.org/wiki/Hierarchical_model-view-controller)
-------------------------------------------------------------------------------------------------------------

[](#hmvc-hierarchical-modelviewcontroller)

For using you must be installed [Rock Response](https://github.com/romeOz/rock-response): `composer require romeoz/rock-response`.

\####Local

```
// url: http://site.com/news/7/

$route = new Route();

$handler = function(Route $route){
    return 'hello';
};

$route->get('/foo/{id:\d+}/', $handler);
$route->post('/bar/{id:\d+}', ['\namespace\BarController', 'actionIndex']);
$route->run();

class BarController
{
    public function actionIndex(\rock\route\Route $route)
    {
        $response = (new \rock\route\providers\Local(['route' => $route]))->send('http://site.com/foo/11/');
        return $response->getContent() . ' world!';
    }
}

// output: 'hello world!'
```

\####Remote

For using you must be installed [Guzzle](https://github.com/guzzle/guzzle): `composer require guzzlehttp/guzzle:6.1.*`.

> Required PHP 5.5+

```
$response = (new \rock\route\providers\Remote())->send('http://site.com/foo/11/');
```

Caching rules
-------------

[](#caching-rules)

For caching rules/groups you must be installed [Rock Cache](https://github.com/romeOz/rock-cache): `composer require romeoz/rock-cache`.

```
$cache = new \rock\cache\Memcached;

$route = new Route([
    'cache' => $cache,
    'enableCache' => true
]);
```

For reset the cache using `flushCache()`:

```
$route->flushCache();
```

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

[](#requirements)

- **PHP 5.4+**
- For using response required [Rock Response](https://github.com/romeOz/rock-response): `composer require romeoz/rock-response`
- For using filters required [Rock Filters](https://github.com/romeOz/rock-filters): `composer require romeoz/rock-filters`
- For using Rate Limiter filter required [Rock Session](https://github.com/romeOz/rock-session): `composer require romeoz/rock-session`
- For caching rules required [Rock Cache](https://github.com/romeOz/rock-cache): `composer require romeoz/rock-cache`
- For using HMVC remote required [Guzzle](https://github.com/guzzle/guzzle): `composer require guzzlehttp/guzzle:6.1.*`.

> All unbolded dependencies is optional.

License
-------

[](#license)

Router is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

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

Total

2

Last Release

3840d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/23c5d84a59845d751cb69f5469986579b9312c54c898b366fefdc05baaa80a9c?d=identicon)[romeOz](/maintainers/romeOz)

---

Top Contributors

[![romeOz](https://avatars.githubusercontent.com/u/3135712?v=4)](https://github.com/romeOz "romeOz (29 commits)")

---

Tags

restrouterroute

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/romeoz-rock-route/health.svg)

```
[![Health](https://phpackages.com/badges/romeoz-rock-route/health.svg)](https://phpackages.com/packages/romeoz-rock-route)
```

###  Alternatives

[contributte/api-router

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

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

PHPackages © 2026

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