PHP code example of mithridatem / router

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

    

mithridatem / router example snippets




ithridatem\Routing\Route;
use Mithridatem\Routing\Router;

$router = new Router();

// Route simple
$router->map(Route::get('/', fn () => 'Hello world'));

// Route avec parametre dynamique
$router->map(Route::get('/books/{id}', function (string $id) {
    return "Livre #$id";
}));

echo $router->dispatch();

use Mithridatem\Routing\Context\RequestContextInterface;

final class FakeContext implements RequestContextInterface
{
    public function __construct(private string $path, private string $method) {}

    public function getPath(): string { return $this->path; }
    public function getMethod(): string { return $this->method; }
    public function getBearerToken(): ?string { return null; }
}

$router->dispatch(new FakeContext('/books/42', 'GET'));

use Mithridatem\Routing\Http\RequestInterface;

$router->map(Route::post('/books/{id}', function (string $id, RequestInterface $request): string {
    $title = $request->post('title');
    if (!is_string($title) || trim($title) === '') {
        return 'Le titre est obligatoire.';
    }

    // Appeler ici le service metier.
    return 'Livre modifie.';
}));

echo $router->dispatch();

use Mithridatem\Routing\Http\FileRequestInterface;

$router->map(Route::post('/upload', function (FileRequestInterface $request): string {
    $file = $request->file('cover');
    if ($file === null || $file->getError() === UPLOAD_ERR_NO_FILE) {
        return 'Aucun fichier selectionne.';
    }
    if (!$file->isValid()) {
        return 'Erreur de transfert : ' . $file->getError();
    }

    // Metadonnees conservees : tmp_name, name, size et error.
    // Valider le contenu puis utiliser le service de stockage.
    return 'Fichier recu : ' . $file->getSize() . ' octets.';
}));

$router->mapController(
    'GET',
    '/admin/dashboard',
    App\Controller\AdminController::class,
    'dashboard'
);

$router->setControllerResolver(new ContainerAwareResolver($container));



namespace App\Controller;

use Mithridatem\Routing\Attribute\Route;

class HomeController
{
    #[Route(path: '/', method: 'GET')]
    public function index(): string
    {
        return 'Accueil';
    }

    #[Route(path: '/books/{id}', method: 'GET')]
    public function show(string $id): string
    {
        return "Livre #$id";
    }
}



namespace App\Controller\Admin;

use Mithridatem\Routing\Attribute\Route;

class DashboardController
{
    #[Route(path: '/admin/dashboard', method: 'GET', grants: ['ROLE_ADMIN'])]
    public function index(): string
    {
        return 'Tableau de bord';
    }
}



ithridatem\Routing\Loader\AttributeRouteLoader;
use Mithridatem\Routing\Router;

$router = new Router();

(new AttributeRouteLoader())->loadDirectory(
    router: $router,
    directory: __DIR__ . '/../src/Controller',
    namespace: 'App\\Controller'
);

echo $router->dispatch();

use Mithridatem\Routing\Auth\ArrayGrantChecker;

$router->setGrantChecker(new ArrayGrantChecker(['ROLE_ADMIN']));

use Mithridatem\Routing\Route;

$router->map(Route::get('/health', fn () => 'OK'));



namespace App\Service;

final class ProductService
{
    public function findName(string $id): string
    {
        return 'Produit #' . $id;
    }
}



namespace App\Controller;

use App\Service\ProductService;
use Mithridatem\Routing\Attribute\Route;

final class ProductController
{
    public function __construct(private ProductService $products)
    {
    }

    #[Route(path: '/products/{id}', method: 'GET')]
    public function show(string $id): string
    {
        return $this->products->findName($id);
    }
}



namespace App\Routing;

use Mithridatem\Routing\Controller\ControllerResolverInterface;
use Mithridatem\Routing\Handler\ControllerReference;
use Mithridatem\Routing\Exception\RouterException;

final class InstanceControllerResolver implements ControllerResolverInterface
{
    /** @param array<class-string, object> $controllers */
    public function __construct(private array $controllers)
    {
    }

    public function resolve(ControllerReference $controller): callable
    {
        $class = $controller->getClassName();
        $method = $controller->getMethodName();
        $instance = $this->controllers[$class] ?? null;

        if ($instance === null) {
            throw new RouterException("Controleur non enregistre : $class");
        }

        if (!is_callable([$instance, $method])) {
            throw new RouterException("Methode non accessible : $class::$method");
        }

        return [$instance, $method];
    }
}



pp\Controller\ProductController;
use App\Routing\InstanceControllerResolver;
use App\Service\ProductService;
use Mithridatem\Routing\Loader\AttributeRouteLoader;
use Mithridatem\Routing\Router;

$products = new ProductService();
$productController = new ProductController($products);

$router = new Router();
$router->setControllerResolver(new InstanceControllerResolver([
    ProductController::class => $productController,
]));

(new AttributeRouteLoader())->loadDirectory(
    router: $router,
    directory: __DIR__ . '/../src/Controller',
    namespace: 'App\\Controller'
);

echo $router->dispatch();

use Mithridatem\Routing\Auth\ArrayGrantChecker;

$router->setGrantChecker(new ArrayGrantChecker(['ROLE_ADMIN']));

$router->map(Route::get('/admin', fn () => 'Admin panel', ['ROLE_ADMIN']));

$router->setBasePath('/mon-app');
bash
composer dump-autoload
text
mon-projet/
├── composer.json
├── public/
│   └── index.php
└── src/
    └── Controller/
        ├── HomeController.php
        └── Admin/
            └── DashboardController.php