PHP code example of ivanmercedes / hermes

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

    

ivanmercedes / hermes example snippets




use Hermes\Attributes\Get;
use Hermes\Attributes\Post;

class UserController
{
    #[Get('/users')]
    public function index(): array
    {
        return ['users' => []];
    }

    #[Get('/users/{id}')]
    public function show(int $id): array
    {
        return ['id' => $id];
    }

    #[Post('/users')]
    public function store(): array
    {
        return ['created' => true];
    }
}



ermes\Router\RouteCollection;
use Hermes\Router\Router;
use Hermes\Router\RouteCompiler;
use Hermes\Router\RouteMatcher;
use Hermes\Router\Exceptions\RouteNotFoundException;

// Initialize router
$collection = new RouteCollection();
$router = new Router($collection);
$router->registerController(UserController::class);

// Compile routes
$compiled = RouteCompiler::compile($collection);
$matcher = new RouteMatcher($compiled);

// Handle request
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

try {
    $match = $matcher->match($method, $uri);
    
    $route = $match['route'];
    $params = $match['params'];
    
    $controller = new ($route->controller)();
    $response = $controller->{$route->action}(...array_values($params));
    
    echo json_encode($response);
} catch (RouteNotFoundException $e) {
    http_response_code(404);
    echo json_encode(['error' => $e->getMessage()]);
}

#[Get('/posts/{id}/comments/{commentId}')]
public function showComment(int $id, int $commentId): array
{
    return [
        'post_id' => $id,
        'comment_id' => $commentId
    ];
}
bash
php -S localhost:8000 examples/server.php

src/
├── Attributes/       # HTTP method attributes (Get, Post, Put, Delete)
├── Contracts/        # Interfaces
└── Router/          # Core routing components
    ├── Route.php
    ├── RouteCollection.php
    ├── RouteCompiler.php
    ├── RouteMatcher.php
    └── Router.php
bash
php -S localhost:8000 examples/server.php