PHP code example of rammewerk / router

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

    

rammewerk / router example snippets


use Rammewerk\Router\Router;

// Define your dependency resolver.
// This is a closure that receives a class string
// and  must return an instance of that class.
$di_container = static fn( string $class) => new $class() );

// Create Router
$router = new Router($di_container);

// Define routes
// ...

// Go!
$response = $router->dispatch();

// Handle response....


$router->add('/hello', function() {
    return 'Hello World!';
});

$router->add('/profile', ProfileRoute::class);

namespace Routes;

class ProfileRoute {

    public function index(): string {
        return 'You visited /profile';
    }

}

class ProfileRoute {

    // Previous methods

    public function settings_notifications(): string {
        return 'You visited /profile/settings/notifications';
    }

}

use Rammewerk\Router\Foundation\Route;

#[Route('/profile')] // <-- must match based path given in add()
class ProfileRoute {

    // Will match /profile/settings/notifications
    #[Route('/settings/notifications')] // <-- Attribute
    #[Route('/profile/settings/notifications')] // <-- This also works
    public function notifications(): string {
        return 'You visited /profile/settings/notifications';
    }
    
}

class ProfileRoute {

    public function edit( int $id ): string {
        return "You visited /profile/edit/$id";
    }
    
}

$router->add('/profile/*/edit', ProfileEditRoute::class);

# Backed enum
enum OrderStatusEnum: string {
    case OPEN = 'open'; // Path Argument /open/ will match this
    case CLOSED = 'closed'; // Path Argument /closed/ will match this
}

# Regular enum
enum OrderShipmentEnum {
    case SHIPPED;   // Path Argument /shipped/ will match this
    case NOT_SHIPPED; // Path Argument /not_shipped/ will match this
}

# Example:

#[Route('/orders')]
class Orders {

    #[Route('/item/*/status')] // Will support paths like: /item/123/status/open
    public function itemStatus( int $item_id, OrderStatusEnum $status ): string {
        return "The status for item $item_id is $status->value";
    }
     
}

class ProfileRoute {
    public function edit( Profile $profile, Template $template, int $id ): Response {
        $user = $profile->find($id);
        return $template->render('profile/edit', [$user]);
    }
}

$router->add(...)->classMethod('edit');

$router = new Router( static fn( string $class_string ) => $container->create($class_string) );

$router->add('/', HomeRoutes::class)->middleware([
    AuthMiddleware::class,
    LoggerMiddleware::class,
]);

class AuthMiddleware {
    public function handle(Request $request, \Closure $next) {
        // Do auth stuff
        return $next($request);
    }
}

$router->dispatch('/profile', new ServerRequest());

$router->group(function(Router $r) {
    $r->add('/products', ProductRoutes::class);
    $r->add('/users', fn() => 'Users listing');
})->middleware([
    AuthMiddleware::class,
    LoggerMiddleware::class
]);

$r->group(function (Router $r) {
    $r->add('/products', ProductRoutes::class)->middleware([AuthMiddleware::class]);
    // More routes
})->middleware([LoggerMiddleware::class]);

try {
    $response = $router->dispatch( path: '/', serverRequest: $request );
    // Handle response
} catch (InvalidRoute $e) {
    // Handle 404 errors or log unmatched paths
} catch (Throwable $e) {
    // Handle other application errors, or let it bubble up
}

// Define a closure-based route with parameter handling and middleware
$router->add('/greet', function (string $name, Logger $logger): string {
  $logger->info("Greeting user: $name");
  return "Hello, $name!";
})->middleware([
    AuthMiddleware::class,
]);

// Dispatch the router
$router->dispatch('/greet/John', new Request());

use Rammewerk\Router\Extension\PsrRouter;

$router = new PsrRouter(static fn(string $class) => $container->get($class));

// Add PSR middleware and routes
// HomeRoute handle method must return a PSR-7 ResponseInterface
$router->add('/home', HomeRoute::class)->middleware([
    AuthMiddleware::class, // Implements PSR-15 MiddlewareInterface
]);

// $serverRequest is a PSR-7 ServerRequestInterface
$response = $router->dispatch('/', $serverRequest);

header('Content-Type: ' . $response->getHeaderLine('Content-Type'));
echo $response->getBody();

use Rammewerk\Router\Foundation\Route;

#[Route('/dashboard')]
class DashboardRoute {
    // ...
}

// Base segment ('/dashboard') matches class-level #Route('/dashboard')
$router->add('/dashboard', DashboardRoute::class); 

#[Route('/dashboard')]
class DashboardRoute {

    #[Route('/stats/*/details')]
    public function stats(string $param1, string ...$wildcards): Response {
        // Example: `/dashboard/stats/123/details/flag1/flag2`
    }

    #[Route('/profile')]
    public function profile( int $id ): string {
        return "Profile page for user ID $id";
    }
    
    public function unknown(): string {
        return 'Will never be called, no matching route found';
    }
    
}