marrios/router

v2.2.3 2023-07-07 19:03 UTC

This package is auto-updated.

Last update: 2024-11-16 18:43:44 UTC


README

Total Downloads Latest Stable Version License

@marriosdev

Marrios/Router

HTTP Route Manager for MVC Projects

Any bug you find, you can open PR


Guide

Starting

0 - Installing

composer require marrios/router

1 - Using functions

   
use Marrios\Router\HttpRouter;

$router = new HttpRouter();

// Set route
$router->get("/helloworld", [function(){ echo "Hello World!";}])->run();
$router->notFound();

When accessing the /helloworld route

   Hello World!

2 - Using Controllers

use App\Controllers\TesteController;

use Marrios\Router\HttpRouter;

$router = new HttpRouter();

// Set route
$router->post("/helloworld", [TesteController::class, "helloWorld"])->run();
$router->notFound();

When accessing the /helloworld route

   Hello World!

Parameters

Using dynamic parameters

Dynamic parameters are defined using curly braces { }

* Note: When defining a dynamic route, you must add a parameter to the callback function or in the controller method


Follow the example below using CallBack:

use Marrios\Router\HttpRouter;

$router = new HttpRouter();

// Set route
$router->post("/blog/{category}/{id_post}", [ function($param){ echo $param->category;}])->run();
$router->notFound();

When accessing the /blog/video/1323 route

   video

Follow the example below using Controller:

use Marrios\Router\HttpRouter;

$router = new HttpRouter();

// Instantiating the route object
$router = new Router();

// Set route
$router->get("/blog/{category}/{id_post}", [TesteController::class, "helloWorld"])->run();
$router->notFound();

Your controller should look like this

class TesteController
{
    public function helloWorld($param)
    {
        echo $param->id_post;
    }
}

When accessing the /blog/video/1323 route

   1323

Routes Group

Implement route groups

Group

$router->group([
    $router->get("ok",  [function () {echo "Hello";}])->run(),
    $router->get("ok2",  [function () {echo "Hello 2";}])->run()
]);

Route Group with Middleware

$router->middleware([Middleware::class])->group([
    $router->get("ok",  [function () {echo "Hello";}])->run(),
    $router->get("ok2",  [function () {echo "Hello 2";}])->run()
]);

Access logs

Enable logs and define the location where the logs will be stored. Note: this line must be defined at the beginning of the file

$router->logs(logs: true)->setStorageLogs(__DIR__);