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

ActiveLibrary

hnrazevedo/router
=================

Router is a simple friendly URL abstractor.

v3.0.6(4y ago)0278MITPHPPHP &gt;=8.0

Since Aug 11Pushed 4y ago1 watchersCompare

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

READMEChangelog (1)Dependencies (2)Versions (57)Used By (0)

Router @HnrAzevedo
==================

[](#router-hnrazevedo)

[![Maintainer](https://camo.githubusercontent.com/635097b3bfe7b55e89a425855fb0567f79aea687d3f7176a187b388ed7c99d56/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d61696e7461696e65722d40686e72617a657665646f2d626c75653f7374796c653d666c61742d737175617265)](https://github.com/hnrazevedo)[![Latest Version](https://camo.githubusercontent.com/747e21fa8626957ddc9652f0bec34caef0afd384578ddb528b9d580aa8636637/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f7461672f686e72617a657665646f2f526f757465723f6c6162656c3d76657273696f6e267374796c653d666c61742d737175617265)](https://github.com/hnrazevedo/Router/releases)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/67715a5f753c59a1cd82813f48d50716ff3449081a50fa58acbc5f333279fe62/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f686e72617a657665646f2f526f757465723f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/hnrazevedo/Router/?branch=master)[![Build Status](https://camo.githubusercontent.com/74060a039d2f6e5a36a46cede52e304d11acadb74d56272e31c0cf4214f34f03/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f6275696c642f672f686e72617a657665646f2f526f757465723f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/hnrazevedo/Router/build-status/master)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![PHP from Packagist](https://camo.githubusercontent.com/69a2e04bb6956179ca3b32914dc2a16fbae7a6438e893813d3249fc08821c19d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f686e72617a657665646f2f526f757465723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hnrazevedo/Router)[![Total Downloads](https://camo.githubusercontent.com/75ed7dee6f2ab0cb8f1fab1e1c8c169cd6d3faa4f87a36e772682b80eb510f53/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686e72617a657665646f2f526f757465723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hnrazevedo/Router)

##### Router is a simple friendly URL abstractor. It can be used in an easy and practical way, either individually in a static way, or together as a middleware and now as an attribute with PHP 8. Its author is not a professional in the development area, just someone in the Technology area who is improving their knowledge.

[](#router-is-a-simple-friendly-url-abstractor-it-can-be-used-in-an-easy-and-practical-way-either-individually-in-a-static-way-or-together-as-a-middleware-and-now-as-an-attribute-with-php-8-its-author-is-not-a-professional-in-the-development-area-just-someone-in-the-technology-area-who-is-improving-their-knowledge)

O Router é um simples abstrator de URL amigável. Ele pode ser utilizada de maneira fácil e prática, tanto individualmente de forma estática, quanto em conjunto como middleware e agora como atributo com o PHP 8. Seu autor não é um profissional da área de desenvolvimento, apenas alguem da área de Tecnologia que está aperfeiçoando seus conhecimentos.

Highlights
----------

[](#highlights)

- Easy to set up (Fácil de configurar)
- Easy information caching (Fácil cacheamento de informações)
- Follows standard PSR-15 (Segue padrão o PSR-15)
- Composer ready (Pronto para o composer)

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

[](#installation)

Router is available via composer.json:

```
"hnrazevedo/router": "^2.4" # PHP = 8.0
```

or in at terminal

```
composer require hnrazevedo/router
```

Configure server
----------------

[](#configure-server)

### Nginx

[](#nginx)

#### nginx.conf

[](#nginxconf)

```
location / {
    index index.php;
    try_files $uri  /index.php$is_args$args;
}

```

### Apache

[](#apache)

#### .htaccess

[](#htaccess)

```

        Options -MultiViews
        Options -Indexes

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

        allow from all

```

Documentation
-------------

[](#documentation)

#### For more details on the use and configuration of the Router, see the example folder with details on component targeting

[](#for-more-details-on-the-use-and-configuration-of-the-router-see-the-example-folder-with-details-on-component-targeting)

Para mais detalhes sobre a utilização e configuração do Router, veja a pasta de exemplos com detalhes no diretório do componente

### Errors

[](#errors)

#### In the static use of the Router, if an inexistent page error is returned, an Exception will be thrown

[](#in-the-static-use-of-the-router-if-an-inexistent-page-error-is-returned-an-exception-will-be-thrown)

#### When used as middleware, a 404 response is returned

[](#when-used-as-middleware-a-404-response-is-returned)

Na utilização estática do Router, caso retorne erro de página inexistente, será lançada uma Exception Na utilização como middleware, é retornado uma resposta 404

### Access methods

[](#access-methods)

#### Available protocols

[](#available-protocols)

- get: URL access or get method
- post: post method
- ajax: called fetch or XMLHttpRequest

#### Ajax

[](#ajax)

#### To use the Ajax call, it is necessary to define REQUEST\_METHOD as AJAX:

[](#to-use-the-ajax-call-it-is-necessary-to-define-request_method-as-ajax)

Para utilizar a chamada Ajax, é necessário a definição do REQUEST\_METHOD como AJAX:

```

    ...

```

#### REST request

[](#rest-request)

- post: REST request
- get: REST request
- put: REST requests
- delete: REST requests
- patch: REST requests

### Router Attributes

[](#router-attributes)

#### Attribute routing works the same as role routing, with just a few caveats:

[](#attribute-routing-works-the-same-as-role-routing-with-just-a-few-caveats)

- Groups are not supported;
- Pre and post functions do not support anonymous functions;
- You must declare the classes with routes in a pipeline and load it with the router.

#### Both means of declaring routes can be used together.

[](#both-means-of-declaring-routes-can-be-used-together)

O roteamento por atributo funciona da mesma forma que o roteamento por função, apenas com algumas resalvas:

- Não há suporte para grupos;
- As funções anteriores e posteriores não tem suporte à funções anônimas;
- Deve-se declarar as classes com rotas em uma pipeline e carrega-la com o roteador.

Ambos os meios de declaração de rotas podem ser usados em conjunto.

```
use HnrAzevedo\Router\Route;

/**
 * @param string $uri
 * @param ?array $methods
 * @param ?string $name
 * @param ?string $before
 * @param ?string $after
 * @param ?array $middleware
 * @param ?array $attributes
 * @param ?array $where
 */
#[Route('/path', name:'routeName')]
```

Example:

```
# Controller File
use HnrAzevedo\Router\Route;

class ControllerAttribute{

    #[Route(
        '/user/{id}',
        methods:['GET'],
        name:'routeName',
        before:'Namespace\Controller@methodBefore',
        middleware:[],
        attributes:[
            'attributeName'=>'attributeValue',
            'attributeName0'=>'attributeValue0'
            ],
        where:['id'=>'[0-9]{1,11}'],
        after:'Namespace\Controller@methodAfter',
    )]
    public function method($param)
    {
        echo 'Controller@method executed!'.PHP_EOL."Param:{$param}";
    }

    public function methodBefore(): void
    {
        echo 'methodBefore'.PHP_EOL;
    }

    public function methodAfter(): void
    {
        echo PHP_EOL.'methodAfter';
    }
}
```

#### It is necessary to load the classes with routes in the same way as the route declaration files, it is interesting for both methods that the loading is done directly by composer.

[](#it-is-necessary-to-load-the-classes-with-routes-in-the-same-way-as-the-route-declaration-files-it-is-interesting-for-both-methods-that-the-loading-is-done-directly-by-composer)

#### Loading can be done directly with a class or with the directory.

[](#loading-can-be-done-directly-with-a-class-or-with-the-directory)

É necessário fazer o carregamento das classes com rotas da mesma forma que os arquivos de declarações de rota, é interessante para ambos os métodos, que o carregamento seja feito diretamente pelo composer.

O carregamento pode ser feito diretamente com uma class ou com o diretório

```
# Pipeline declaration
use HnrAzevedo\Router\Router;

Router::pipeline([
    HnrAzevedo\Router\Example\Controllers\ControllerAttribute::class,
    'examples\Controllers'
]);
```

### Router methods

[](#router-methods)

### get

[](#get)

```
Router::get('/','App\Controller\Application@method');
```

### post

[](#post)

```
Router::post('/controller/method','App\Controller\Application@method');
```

### ajax

[](#ajax-1)

```
Router::ajax('/userList','foo\bar\User@listme');
```

### middleware

[](#middleware)

```
Router::globalMiddlewares([
    'Authorization'=> \App\Middlewares\Authorization::class
])

Router::get('/foo','foo\bar\User@method')->middleware([
    \App\Middlewares\Authentication::class,
    'Authorization'
]);
```

### name

[](#name)

#### Defines a name for the route, if you want to call dynamically by name

[](#defines-a-name-for-the-route-if-you-want-to-call-dynamically-by-name)

```
Router::get('/','foo@bar')->name('index');
```

### attribute

[](#attribute)

#### Defines attributes to route, to be used dynamically

[](#defines-attributes-to-route-to-be-used-dynamically)

```
/**
 * @param string $name
 * @param $value
 */
Router::get('/','foo@bar')->attribute('permission','permissionName');
```

#### Returning an attribute

[](#returning-an-attribute)

```
/**
 * @param string $name
 */
$permission = Router::getAttribute('attributeName');
```

#### Returning all attributes

[](#returning-all-attributes)

```
$permissions = Router::getAttributes();
```

### before

[](#before)

#### Runs before starting the work of the accessed route

[](#runs-before-starting-the-work-of-the-accessed-route)

```
Router::get('/foo/bar','foo@bar')
      ->before('foo@beforeMethod');

Router::get('/foo/bar','foo@bar')
      ->before(function(){
          //
      });
```

### after

[](#after)

#### Executes after completing the work of the accessed route

[](#executes-after-completing-the-work-of-the-accessed-route)

```
Router::get('/bar/foo','bar@foo')
      ->after('bar@afterMethod');

Router::get('/bar/foo','bar@foo')
      ->after(function(){
          //
      });
```

### beforeAll

[](#beforeall)

#### Runs before work on any route

[](#runs-before-work-on-any-route)

#### NOTE: execute the beforeAll method before the before method

[](#note-execute-the-beforeall-method-before-the-before-method)

```
/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::beforeAll('foo@bar');
Router::beforeAll('foo@bar',['Except_route','Outer_route']);
Router::beforeAll(function(){
          //
      });
```

### after All

[](#after-all)

#### Runs after completing work on any route

[](#runs-after-completing-work-on-any-route)

#### NOTE: execute the afterAll method before the after method

[](#note-execute-the-afterall-method-before-the-after-method)

```
/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::afterAll('bar@foo');
Router::afterAll('bar@foo',['Except_route','Outer_route']);
Router::afterAll(function(){
          //
      });
```

### group

[](#group)

#### Set the group to use a common filter or before/after methods

[](#set-the-group-to-use-a-common-filter-or-beforeafter-methods)

```
/**
 * @param string $prefix
 * @param \Closure $definitions
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
});
```

### groupAttribute

[](#groupattribute)

#### Defines attributes on all routes in the group

[](#defines-attributes-on-all-routes-in-the-group)

#### NOTE:If the attribute has already been defined directly on the route, it will be disregarded here

[](#noteif-the-attribute-has-already-been-defined-directly-on-the-route-it-will-be-disregarded-here)

```
/**
 * @param string $name
 * @param $value
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
})->groupAttribute('permission','permissionName');
```

### groupMiddlewares

[](#groupmiddlewares)

#### Defines middleware for all group members

[](#defines-middleware-for-all-group-members)

```
/**
 * @param array $middlewares
 * @param ?array $excepts
 */
Router::group('/foo', function(){
    //
})->groupMiddlewares([
    'Authorization'
]);
```

### beforeGroup | afterGroup

[](#beforegroup--aftergroup)

#### Defines actions to be taken before and after any group member is triggered

[](#defines-actions-to-be-taken-before-and-after-any-group-member-is-triggered)

```
/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
})->beforeGroup(function(){
    //
});

/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
})->afterGroup(function(){
    //
});
```

### REST

[](#rest)

```
Router::delete('pattern','Namespaces\\Controller:method');
Router::get('pattern','Namespaces\\Controller:method');
Router::post('pattern','Namespaces\\Controller:method');
Router::put('pattern','Namespaces\\Controller:method');
Router::patch('pattern','Namespaces\\Controller:method');
```

Parameters
----------

[](#parameters)

```
Router::get('/{param}', function($param){
    //
});

Router::get('/{param}/{param2}', function($param, $param2){
    //
});
```

Optional parameters
-------------------

[](#optional-parameters)

```
Router::get('/foo/{?id}','foo@bar');

Router::get('/foo/{?any}/{?id}','foo@baz');

Router::get('/user/{?id}/{text}','foo@bat');
```

### Regular Expression Constraints

[](#regular-expression-constraints)

```
Router::get('/test/{id}/{id2}',function(){
    //
})->where([
    'id'=>'[0-9]{1,11}',
    'id2' => '[0-9]*'
]);

Router::group('/bar', function(){
    //
})->groupWhere([
    'id'=>'[0-9]{1,11}',
    'id2' => '[0-9]*'
]);
```

Route definition
----------------

[](#route-definition)

### Protocols

[](#protocols)

```
/* Unique protocol */
Router::get('/get','foo@bar');

/* Multiple protocols */
Router::match('POST|get|AjAx','/my-account','baz@bar');

/* All protocols */
Router::any('/any','all@met');
```

### Current route

[](#current-route)

```
$route = Router::current();

$name = Router::currentRouteName();

$action = Router::currentRouteAction();
```

### load

[](#load)

```
/* NOTE: in case of error an exception is thrown */

/* Load the route via the URL accessed on the Router object */
Router::load();
/* Load the route via the name passed to the Router object */
Router::load('bar');

/* After loading the route it is necessary to fire it */
/* NOTE: After loading the route, if any dispatch function name is passed, it will be ignored. */
Router::load('foo')->run();

Router::load();
$currentRouter = Router::current();
Router::run();
```

### run

[](#run)

```
/* NOTE: in case of error an exception is thrown */

/* Trigger route via URL accessed */
Router::run();
/* Trigger route by the given name */
Router::run('baz');
```

### Cache

[](#cache)

```
/* Returns the routes already defined for caching */
$routes = Router::routes();
/* Pass cached routes to the router */
Router::routes($routes);
```

#### Example of caching in SESSION

[](#example-of-caching-in-session)

```
if(!isset($_SESSION['cache']['routes'])){
    //Import routes
    $path = BASEPATH.'/../routes';

    foreach (scandir($path) as $routeFile) {
        if(pathinfo($path.DIRECTORY_SEPARATOR.$routeFile, PATHINFO_EXTENSION) === 'php'){
            require_once($path. DIRECTORY_SEPARATOR .$routeFile);
        }
    }

    $_SESSION['cache']['router']['middlewares'] = Router::globalMiddlewares();
    $_SESSION['cache']['router']['routes'] = Router::routes();
}

Router::routes($_SESSION['cache']['router']['routes']);
Router::globalMiddlewares($_SESSION['cache']['router']['middlewares']);
```

### Definition order

[](#definition-order)

#### Routing loading is a priority with static routes (without parameters)

[](#routing-loading-is-a-priority-with-static-routes-without-parameters)

O carregamento das rotas é prioritário com as rotas estáticas (sem paramêtros)

Support
-------

[](#support)

##### Security: If you discover any security related issues, please email  instead of using the issue tracker.

[](#security-if-you-discover-any-security-related-issues-please-email-hnrazevedogmailcom-instead-of-using-the-issue-tracker)

Se você descobrir algum problema relacionado à segurança, envie um e-mail para  em vez de usar o rastreador de problemas.

Credits
-------

[](#credits)

- [Henri Azevedo](https://github.com/hnrazevedo) (Developer)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/hnrazevedo/Router/blob/master/LICENSE.md) for more information.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

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

Recently: every ~0 days

Total

56

Last Release

1650d ago

Major Versions

v1.8.2 → v2.0.02020-10-02

v2.4.5 → v3.0.02021-11-03

PHP version history (2 changes)v1.0.0PHP &gt;=7.4

v3.0.0PHP &gt;=8.0

### Community

Maintainers

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

---

Top Contributors

[![hnrazevedo](https://avatars.githubusercontent.com/u/56831533?v=4)](https://github.com/hnrazevedo "hnrazevedo (160 commits)")

### Embed Badge

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

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

###  Alternatives

[hellogerard/jobby

Manage all your cron jobs without modifying crontab. Handles locking, logging, error emails, and more.

1.1k1.6M14](/packages/hellogerard-jobby)[binarcode/laravel-mailator

Laravel email scheduler

247293.8k](/packages/binarcode-laravel-mailator)[facuz/laravel-themes

Theme will help you organize your themes inside Laravel projects easily and maintain its related assets, layouts and partials for the theme in single directory. (Based on teepluss/theme)

13843.0k2](/packages/facuz-laravel-themes)[weblabormx/laravel-front

Front is a administration panel for Laravel. It allows you to create CRUD easily in minutes. It allows to fully customize any part of the code.

1111.1k](/packages/weblabormx-laravel-front)[infocyph/intermix

A Collection of useful PHP class functions.

136.4k1](/packages/infocyph-intermix)[dtyq/php-mcp

PHP implementation of MCP server and client

289.9k2](/packages/dtyq-php-mcp)

PHPackages © 2026

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