PHP code example of kissous / attribute-router

1. Go to this page and download the library: Download kissous/attribute-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/ */

    

kissous / attribute-router example snippets


use Kissous\AttributeRouter\Attribute\Route;

final class UserController
{
    #[Route('/users', method: 'GET', name: 'user.index')]
    public function index(): string
    {
        return 'all users';
    }

    #[Route('/users/{id}', method: 'GET', name: 'user.show')]
    public function show(string $id): string
    {
        return "user #{$id}";
    }
}

use Kissous\AttributeRouter\Dispatcher\Dispatcher;

$dispatcher = Dispatcher::fromCompiledFile(__DIR__ . '/var/routes.compiled.php');

$result = $dispatcher->dispatch($request); // any PSR-7 ServerRequestInterface

if ($result->isNotFound()) {
    http_response_code(404);
    return;
}

if ($result->isMethodNotAllowed()) {
    http_response_code(405);
    header('Allow: ' . implode(', ', $result->allowedMethods));
    return;
}

// Matched: $result->controller, $result->action, $result->parameters, $result->name
$controller = new ($result->controller)();
echo $controller->{$result->action}(...$result->parameters);
bash
vendor/bin/attribute-router compile --scan=src/Controller --out=var/routes.compiled.php