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

ActiveLibrary[Framework](/categories/framework)

torugo/router
=============

Simple route system using PHP Attributes

1.0.7(10mo ago)040MITPHPPHP &gt;=8.2

Since Jun 13Pushed 10mo ago1 watchersCompare

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

READMEChangelogDependencies (2)Versions (9)Used By (0)

Router
=======

[](#router-)

A simple PHP router system.
Uses the [PHP Attributes](https://www.php.net/manual/en/language.attributes.php) feature.

Table of Contents
==================

[](#table-of-contents-)

- [Requirements](#requirements)
- [Installing](#installing)
- [Usage](#usage)
    - [Routing](#routing)
    - [Registering Controllers](#registering-controllers)
    - [Resolving the requests](#resolving-the-requests)
        - [Auto Resolve](#auto-resolve)
        - [Resolving manually](#resolving-manually)
        - [Prefixing all routes](#prefixing-all-routes)
    - [Getting request data](#getting-request-data)
    - [Responses](#responses)
    - [Full example](#full-example)
- [Tests](#tests)
    - [With Makefile](#with-makefile)
    - [Manually](#manually)
- [Contribute](#contribute)
- [License](#license)

Requirements
============

[](#requirements)

- PHP 8.2+
- Composer 2+ (Package manager)
- PHPUnit 11+ (Automated tests)

Installing
==========

[](#installing)

```
composer require torugo/router
```

Usage
=====

[](#usage)

Routing
-------

[](#routing)

```
use Torugo\Router\Attributes\Request\Controller;
use Torugo\Router\Attributes\Request\Get;

#[Controller("/users")]
class UsersController {
    #[Get()] // endpoint: GET /users
    public function findAll(): array
    {
        return [/* list of users */];
    }

    #[Get("/{id}")] // endpoint: GET /users/
    public function findOne(string $id): array
    {
        return [/* user data */];
    }
}
```

Registering Controllers
-----------------------

[](#registering-controllers)

All controllers must use the Controller attribute.

```
use Torugo\Router\Router;

$router = new Router;

$router->registerMany([
    UsersController::class,
    CostumersController::class,
    SuppliersController::class,
    StockController::class,
]);

try {
    $router->autoResolve();
} catch (\Throwable $th) {
    // Handle errors
}
```

Additionally you can register controllers individually.

```
$router->register(UsersController::class);
$router->register(CostumersController::class);
$router->register(SuppliersController::class);
$router->register(StockController::class);
```

Resolving the requests
----------------------

[](#resolving-the-requests)

### Auto Resolve

[](#auto-resolve)

```
try {
    $router->autoResolve();
} catch (\Throwable $th) {
    // Handle errors
}
```

### Resolving manually

[](#resolving-manually)

```
$uri = Request::getUri();
$requestMethod = Request::getMethod();

// Here you can filter the uri
// The request method must be a member of RequestMethod Enum

try {
    $router->resolve($uri, $requestMethod);
} catch (\Throwable $th) {
    // Handle errors
}
```

### Prefixing all routes

[](#prefixing-all-routes)

If your API has a prefixed route like `'/v1'` you can configure the router to handle it.

```
use Torugo\Router\Router;

$router = new Router;
$router->setPrefix("/v1");

/**
 * If you receive a GET request with the URI '/v1/users/12345', the router will execute '/users/12345'
 */
```

Getting request data
--------------------

[](#getting-request-data)

You can access the request data anywhere using the method `getData()` from `Torugo\Router\Request`.

```
use Torugo\Router\Attributes\Request\Controller;
use Torugo\Router\Attributes\Request\Post;
use Torugo\Router\Request;

#[Controller("/users")]
class UsersController {
    #[Post()]
    public function add(): array
    {
        $userData = Request::getData();

        /* ADD NEW USER DATA ON DATABASE */

        return [/* new user data */];
    }
}
```

Responses
---------

[](#responses)

When a controller method returns array it is converted to a Json string, other types are not converted.

```
use Torugo\Router\Attributes\Request\Controller;
use Torugo\Router\Attributes\Request\Get;

#[Controller("users")]
class UsersController {
    #[Get()]
    public function findAll(): array
    {
        $users = [
            [
                "id" => "1",
                "name" => "User 1",
                "email" => "user1@host.com"
            ],
            [
                "id" => "2",
                "name" => "User 2",
                "email" => "user2@host.com"
            ],
            [
                "id" => "3",
                "name" => "User 3",
                "email" => "user3@host.com"
            ],
        ];

        return $users;
        // '[{"id":"1","name":"User 1","email":"user1@host.com"},{"id":"2","name":"User ... ]'
    }
}
```

Full example
------------

[](#full-example)

- Controller class

    ```
