PHP code example of fatjon-lleshi / antares-router

1. Go to this page and download the library: Download fatjon-lleshi/antares-router library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fatjon-lleshi / antares-router example snippets


use Antares\Router\Attributes\Get;
use Antares\Router\Attributes\Post;
use Antares\Router\Attributes\Put;
use Antares\Router\Attributes\Patch;
use Antares\Router\Attributes\Delete;

class UserController
{
    #[Get('/users')]
    public function index(): void {}

    #[Get('/users/{id}')]
    public function show(): void {}

    #[Post('/users', 201)]
    public function store(): void {}

    #[Put('/users/{id}')]
    public function update(): void {}

    #[Patch('/users/{id}')]
    public function edit(): void {}

    #[Delete('/users/{id}', 204)]
    public function destroy(): void {}
}

use Antares\Router\Router;

return function(Router $router): void {
    $router->register(UserController::class);
    $router->register(ProductController::class);
    $router->register(OrderController::class);
};

use Antares\Router\Router;

$router = new Router();
$register = teParams, $statusCode] = $router->match(
        $_SERVER['REQUEST_METHOD'],
        parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
    );

    $controller = new $controllerClass();
    $controller->$method();
} catch (\RuntimeException $e) {
    http_response_code($e->getCode());
    echo json_encode(['error' => $e->getMessage()]);
}

[$controller, $method, $params, $status] = $router->match('GET', '/users/42');

echo $params['id']; // "42"

#[Post('/users', 201)]
public function store(): void {}

#[Delete('/users/{id}', 204)]
public function destroy(): void {}

$router->registerFromConfig([
    ['GET',    '/users',      UserController::class, 'index',   200],
    ['POST',   '/users',      UserController::class, 'store',   201],
    ['GET',    '/users/{id}', UserController::class, 'show',    200],
    ['PUT',    '/users/{id}', UserController::class, 'update',  200],
    ['DELETE', '/users/{id}', UserController::class, 'destroy', 204],
]);

$router->registerFromYaml(__DIR__ . '/../routes.yaml');

$cachePath = __DIR__ . '/../storage/cache/routes.php';

if (file_exists($cachePath)) {
    $router->loadFromCache($cachePath);
} else {
    $register = 

try {
    [$controller, $method, $params, $status] = $router->match('GET', '/not-found');
} catch (\RuntimeException $e) {
    $e->getCode(); // 404 = not found, 405 = method not allowed
}

project/
├── public/
│   └── index.php
├── app/
│   └── Controllers/
│       ├── UserController.php
│       └── ProductController.php
├── routes.php
└── composer.json