PHP code example of willy68 / pg-router

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

    

willy68 / pg-router example snippets


use Pg\Router\Router;
use guzzlehttp\Psr7\Response;
use guzzlehttp\Psr7\ServerRequest;

$request = ServerRequest::fromGlobals(); // Create a PSR-7 request from global variables
$router = new Router();

$router->route('/hello/{name: \w+}', function ($request): ResponseInterface {
    $name = $request->getAttribute('name');
    (return new Response())->getBody()->write("Hello, $name!");
}, 'hello', ['GET']);

$res = $router->match($request);

if ($res->isSuccess()) {
// add route attributes to the request
    foreach ($res->getMatchedAttributes() as $key => $val) {
        $request = $request->withAttribute($key, $val);
    }

$callback = $res->getMatchedRoute()->getCallback();
$response = $callback($request);

// Simple parameter, id matches any alphanumeric string
$router->route('/user/{id}','handler', 'user.show', ['GET']);

//Define route parameters with custom patterns:
// Parameter with regex constraint 
$router->route('/user/{id:\d+}','handler', 'user.show', ['GET']);

// Multiple parameters 
$router->route('/blog/{year:\d{4}}/{month:\d{2}}/{slug}','handler', 'blog.post', ['GET']);

// The id matches a numeric string for this route
$route = $router->route('/user/{id}','handler', 'user.show', ['GET'])
    ->setTokens(['id' => '\d+']);

// Default token for all routes before adding a new one
$router->setTokens(['id' => '\d+']);
// Or with The Configuration in the constructor
$router = new Router(
    null,
    null,
    [Router::CONFIG_DEFAULT_TOKENS => ['id' => '[0-9]+', 'slug' => '[a-zA-Z-]+[a-zA-Z0-9_-]+']]
);

// Update and/or add tokens given by the Router
$route->updateTokens(['id' => '[0-9]+', 'slug' => '[a-zA-Z0-9_-]+']);


// Example route with optional segments
$router->route('/article[!/{id: \d+};/{slug: [\w-]+}]', function ($request) {
    $id = $request->getAttribute('id', null);
    $slug = $request->getAttribute('slug', null);
    // ...
}, 'article.show', ['GET']);

$router->group('/api/v1', function ($group) { 
    $group->route('/users', 'UserController::index', 'api.users.index', ['GET']);
    $group->route('/users/{id:\d+}', 'UserController::show', 'api.users.show', ['GET']); 
    $group->route('/users', 'UserController::store', 'api.users.store', ['POST']); 
})->middlewares([AuthMiddleware::class, ApiMiddleware::class]);


// Route-level middleware
$router->route('/admin/dashboard','handler', 'admin.dashboard', ['GET'])
    ->middlewares([AuthMiddleware::class, AdminMiddleware::class]);

// Group-level middleware
$router->group('/admin', function ($group) { 
    $group->route('/users', 'AdminController::users', 'admin.users', ['GET']);
    $group->route('/settings', 'AdminController::settings', 'admin.settings', ['GET']);
})->middlewares([AuthMiddleware::class, AdminMiddleware::class]);


// Define a named route
$router->route('/user/{id:\d+}','handler', 'user.profile', ['GET']);

// Generate URL
$url = $router->generateUri('user.profile', ['id' => 123]); 
// Result: /user/123

// Generate URL with query parameters
$url = $router->generateUri('user.profile', ['id' => 123], ['tab' => 'settings']); 
// Result: /user/123?tab=settings


$router->crud('/posts', PostController::class, 'posts');

// Basic URL generation
$url = $router->generateUri('hello', ['name' => 'Alice']);
// With query parameters
$url = $router->generateUri('user.profile', ['id' => 123], ['tab' => 'settings']);


// Enable caching with a cache file
      $router = new Router (
           null,
           null,
           [
               Router::CONFIG_CACHE_ENABLED => ($env === 'prod'),
               Router::CONFIG_CACHE_DIR => '/tmp/cache',
               Router::CONFIG_CACHE_POOL_FACTORY => function (): CacheItemPoolInterface {...},
           ]
      )

// In production, routes are cached and loaded from the cache file
// In development, disable caching or clear cache when routes change
$router->clearCache();

use Pg\Router\Cache\FileCache;
use Pg\Router\RegexCollector\MarkRegexCollector;
use Pg\Router\RegexCollector\NamedRegexCollector;
use Pg\Router\RegexParser\FastMarkParser;

// Initialize the cache with a custom directory
$fileCache = new FileCache(
    cacheDir: __DIR__ . '../tmp/cache/router',  // Directory to store cache files
    useCache: true                                // Enable caching
);

// Example of using the cache with a route collection
$collectors = [
    'MarkRegexCollector' => new MarkRegexCollector(),
    'NamedCollector' => new NamedRegexCollector(),
    'FastMarkCollector' => new MarkRegexCollector(new FastMarkParser()),
    // Add other collectors if needed
];

// Sample routes
$allRoutes = [
    // Your route definitions here
];

foreach ($collectors as $name => $collector) {
    $collector->addRoutes($allRoutes);
    $hasCache = $fileCache->has($name);
    
    // Fetch data with caching
    // The callback will only execute if the cache is empty
    $startTime = microtime(true);
    $routesData = $fileCache->fetch($name, [$collector, 'getData']);
    $duration = microtime(true) - $startTime;

    echo "<h2>Collector: $name</h2>";
    echo "<div style='color:green;'>";
    echo "Execution time: " . number_format($duration * 1000, 4) . " ms<br>";
    echo "Cached: " . ($hasCache ? 'Yes' : 'No') . "<br>";
    echo "</div>";
}

// Clear specific cache if needed
// $fileCache->delete('MarkRegexCollector');

// Or clear all caches
// $fileCache->clear();

$data = $fileCache->fetch($name, [$collector, 'getData']);
$matcher = new \Pg\Router\Matcher\MarkDataMatcher($data);
$matches = $matcher->match('/post/{id: \d+}', 'GET');