PHP code example of joby / smol-router

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

    

joby / smol-router example snippets


use Joby\Smol\Router\Router;
use Joby\Smol\Router\Matchers\ExactMatcher;
use Joby\Smol\Response\Response;
use Joby\Smol\Response\Status;

$router = new Router();

// will match both GET and POST requests by default
$router->add(
    new ExactMatcher('about'),
    fn() => new Response(new Status(200))
);

$response = $router->run($request);

// Convert to lowercase
$router->routeNormalizer(fn(string $route) => strtolower($route));

// The built-in normalization (trim slashes) runs after custom normalization

use Joby\Smol\Router\Router;
use Joby\Smol\Router\Matchers\ExactMatcher;
use Joby\Smol\Response\Response;
use Joby\Smol\Response\Status;

$router = new Router();

// will only match GET requests
$router->get(
    new ExactMatcher('about'),
    fn() => new Response(new Status(200))
);

$response = $router->run($request);

use Joby\Smol\Router\Router;
use Joby\Smol\Router\Matchers\ExactMatcher;
use Joby\Smol\Response\Method;
use Joby\Smol\Response\Response;
use Joby\Smol\Response\Status;

$router = new Router();

// will only match PATCH and PUT requests
$router->get(
    new ExactMatcher('about'),
    fn() => new Response(new Status(200)),
    method: [Method::PATCH, Method::PUT]
);

$response = $router->run($request);

$router->add(
    new ExactMatcher('about'),
    fn() => new Response(new Status(200))
);
// Matches: about
// Doesn't match: about/team, contact

$router->add(
    new PatternMatcher('users/:id'),
    fn(string $id) => new Response(new Status(200))
);
// Matches: users/123, users/abc
// Doesn't match: users, users/123/posts

$router->add(
    new PatternMatcher('posts/:post_id/comments/:comment_id'),
    fn(string $post_id, string $comment_id) => /* ... */
);
// Matches: posts/456/comments/789

$router->add(
    new CatchallMatcher(),
    fn() => new Response(new Status(404))
);

// Basic usage - captures remainder automatically
$router->add(
    new PrefixMatcher('api/'),
    fn(string $prefix_remainder) => /* ... */
);
// Matches: api/users → $prefix_remainder = 'users'
// Matches: api/posts/123 → $prefix_remainder = 'posts/123'

// Custom parameter name
$router->add(
    new PrefixMatcher('files/', 'path'),
    fn(string $path) => /* ... */
);
// Matches: files/document.pdf → $path = 'document.pdf'

// Disable capture
$router->add(
    new PrefixMatcher('api/', null),
    fn() => /* ... */
);

// Basic usage - captures remainder automatically
$router->add(
    new PrefixPatternMatcher(':tenant/api/'),
    fn(string $tenant, string $prefix_remainder) => /* ... */
);
// Matches: acme/api/users → $tenant = 'acme', $prefix_remainder = 'users'
// Matches: acme/api/posts/123 → $tenant = 'acme', $prefix_remainder = 'posts/123'

// Custom parameter name for remainder
$router->add(
    new PrefixPatternMatcher(':tenant/files/', 'path'),
    fn(string $tenant, string $path) => /* ... */
);
// Matches: acme/files/document.pdf → $tenant = 'acme', $path = 'document.pdf'

// Disable capture
$router->add(
    new PrefixPatternMatcher(':tenant/api/', null),
    fn(string $tenant) => /* ... */
);

// Basic usage - captures base automatically
$router->add(
    new SuffixMatcher('.json'),
    fn(string $suffix_base) => /* ... */
);
// Matches: users.json → $suffix_base = 'users'
// Matches: posts/123.json → $suffix_base = 'posts/123'

// Custom parameter name
$router->add(
    new SuffixMatcher('.json', 'resource'),
    fn(string $resource) => /* ... */
);
// Matches: users.json → $resource = 'users'

// Disable capture
$router->add(
    new SuffixMatcher('.json', null),
    fn() => /* ... */
);

// Basic usage - captures remainder automatically
$router->add(
    new SuffixPatternMatcher('api/:tenant'),
    fn(string $tenant, string $suffix_remainder) => /* ... */
);
// Matches: users/api/acme → $tenant = 'acme', $suffix_remainder = 'users'
// Matches: posts/123/api/acme → $tenant = 'acme', $suffix_remainder = 'posts/123'

// Custom parameter name for remainder
$router->add(
    new SuffixPatternMatcher('api/:tenant', 'resource'),
    fn(string $tenant, string $resource) => /* ... */
);
// Matches: users/api/acme → $tenant = 'acme', $resource = 'users'

// Disable capture
$router->add(
    new SuffixPatternMatcher('api/:tenant', null),
    fn(string $tenant) => /* ... */
);

// Case-insensitive matching
$lowercase = new TransformerMatcher(fn(string $p) => strtolower($p));
$router->add(
    $lowercase->with(new ExactMatcher('about')),
    fn(string $original_path) => /* ... */
);
// Matches: 'ABOUT', 'About', 'about' → $original_path = original casing

// Remove query strings
$router->add(
    new TransformerMatcher(fn(string $p) => explode('?', $p)[0])
        ->with(new ExactMatcher('search')),
    fn() => /* ... */
);
// Matches: 'search?q=test', 'search?filter=all'

// Custom parameter name for original path
$router->add(
    new TransformerMatcher(fn($p) => strtolower($p), 'raw_path')
        ->with(new PatternMatcher('users/:id')),
    fn(int $id, string $raw_path) => /* ... */
);
// Matches: 'USERS/123' → $id = 123, $raw_path = 'USERS/123'

// Disable capturing original path
$router->add(
    new TransformerMatcher(fn($p) => urldecode($p), null)
        ->with(new PatternMatcher('search/:query')),
    fn(string $query) => /* ... */
);

// Match api/users/:id pattern
$api = new PrefixMatcher('api/');
$router->add(
    $api->with(new PatternMatcher('users/:id')),
    fn(int $id, string $prefix_remainder) => /* ... */
);
// Matches: api/users/123 → $id = 123, $prefix_remainder = 'users/123'

$tenant = new PrefixPatternMatcher(':tenant/');
$versioned = $tenant->with(new PrefixPatternMatcher('api/v:version/'));
$composed = $versioned->with(new PatternMatcher('users/:id'));

$router->add(
    $composed,
    fn(string $tenant, string $version, int $id) => /* ... */
);
// Matches: acme/api/v2/users/123 → $tenant = 'acme', $version = '2', $id = 123

$apiV1 = new PrefixMatcher('api/v1/');

$router->add(
    $apiV1->with(new PatternMatcher('users/:id')),
    fn(int $id) => /* handle user */
);

$router->add(
    $apiV1->with(new PatternMatcher('posts/:id')),
    fn(int $id) => /* handle post */
);

$router->add(
    $apiV1->with(new SuffixMatcher('.json')),
    fn() => /* handle JSON endpoints */
);

// Match users/:id.json with case-insensitive matching
$lowercase = new TransformerMatcher(fn($p) => strtolower($p));
$json = new SuffixMatcher('.json');

$router->add(
    $lowercase->with($json->with(new PatternMatcher('users/:id'))),
    fn(int $id, string $original_path) => /* ... */
);
// Matches: USERS/123.JSON → $id = 123, $original_path = 'USERS/123.JSON'

// Match api/:version/users/:id.json
$api = new PrefixPatternMatcher('api/:version/');
$json = new SuffixMatcher('.json');

$router->add(
    $api->with($json->with(new PatternMatcher('users/:id'))),
    fn(string $version, int $id) => /* ... */
);
// Matches: api/v2/users/123.json → $version = 'v2', $id = 123

// String parameters
$router->add(
    new PatternMatcher('users/:id'),
    fn(string $id) => /* $id is a string */
);

// Typed parameters (automatically converted)
$router->add(
    new PatternMatcher('users/:id'),
    fn(int $id) => /* $id is converted to int */
);

// Multiple parameters
$router->add(
    new PatternMatcher('posts/:id/page/:page'),
    fn(int $id, int $page) => /* both converted to int */
);

// Request injection
// To get the full Request object, add a typed parameter named "$request"
$router->add(
    new ExactMatcher('info'),
    fn(Request $request) => /* receives the full request object */
);

// Path injection
// To get the full matched path, add a string parameter called "$path"
$router->add(
    new PatternMatcher('users/:id'),
    fn(string $path, int $id) => /* $path = 'users/123', $id = 123 */
);

use Joby\Smol\Request\Method;

$router->add(
    new ExactMatcher('login'),
    fn() => /* ... */,
    Method::POST
);

$router->add(
    new PatternMatcher('users/:id'),
    fn(int $id) => /* ... */,
    [Method::GET, Method::HEAD]
);

use Joby\Smol\Router\Priority;

// Checked first
$router->add(
    new ExactMatcher('special'),
    fn() => /* ... */,
    priority: Priority::HIGH
);

// Checked second (default)
$router->add(
    new PrefixMatcher('api/'),
    fn() => /* ... */,
    priority: Priority::NORMAL
);

// Checked last
$router->add(
    new CatchallMatcher(),
    fn() => /* ... */,
    priority: Priority::LOW
);

use Joby\Smol\Router\Priority;

// Basic authentication guard
$router->guard(
    new PrefixMatcher('admin/'),
    function (Request $request): bool|null {
        if (!isset($_SESSION['user'])) {
            return false; // Deny access (403)
        }
        return null; // Allow further processing
    }
);

// Role-based access control
$router->guard(
    new PrefixMatcher('admin/'),
    function (): bool {
        return $_SESSION['role'] === 'admin'; // true = allow, false = deny
    },
    priority: Priority::HIGH
);

// Guards support the same parameter injection as handlers
$router->guard(
    new PatternMatcher('users/:id/edit'),
    function (int $id, Request $request): bool|null {
        $currentUser = $_SESSION['user_id'] ?? null;
        if ($currentUser !== $id) {
            return false; // Users can only edit their own profile
        }
        return null;
    }
);

// Only guard POST requests
$router->guard(
    new PrefixMatcher('api/'),
    fn() => checkCsrfToken() ? null : false,
    method: Method::POST
);

// Guard multiple methods
$router->guard(
    new PrefixMatcher('admin/'),
    fn() => isAuthenticated() ? null : false,
    method: [Method::POST, Method::PUT, Method::DELETE]
);

// Check authentication first
$router->guard(
    new CatchallMatcher(),
    fn() => isAuthenticated() ? null : false,
    priority: Priority::HIGH
);

// Then check specific permissions
$router->guard(
    new PrefixMatcher('admin/'),
    fn() => hasAdminRole() ? null : false,
    priority: Priority::NORMAL
);

// Add CORS headers to all API responses
$router->modify(
    new PrefixMatcher('api/'),
    function (Response $response): Response {
        $response->headers->set('Access-Control-Allow-Origin', '*');
        return $response;
    }
);

// Convert objects to JSON
$router->modify(
    new SuffixMatcher('.json'),
    function (Response $response): Response {
        if ($response->content instanceof MyDataObject) {
            $json = json_encode($response->content->toArray());
            $response->setContent(new StringContent($json));
            $response->headers->set('Content-Type', 'application/json');
        }
        return $response;
    }
);

// Modifiers also receive matched parameters
$router->modify(
    new PatternMatcher('api/:version'),
    function (string $version, Response $response): Response {
        $response->headers->set('API-Version', $version);
        return $response;
    }
);

// First modifier (runs first)
$router->modify(
    new CatchallMatcher(),
    function (Response $response): Response {
        $response->headers->set('X-Powered-By', 'smolRouter');
        return $response;
    },
    priority: Priority::HIGH
);

// Second modifier (runs after the first)
$router->modify(
    new CatchallMatcher(),
    function (Response $response): Response {
        $response->headers->set('X-Request-ID', uniqid());
        return $response;
    },
    priority: Priority::NORMAL
);

// Only modify POST responses
$router->modify(
    new PrefixMatcher('api/'),
    fn(Response $response) => addCreatedTimestamp($response),
    method: Method::POST
);

$router->typeHandler(DateTime::class, function (string $value): ?DateTime {
    try {
        return new DateTime($value);
    } catch (Exception $e) {
        return null;
    }
});

$router->add(
    new PatternMatcher('events/:date'),
    fn(DateTime $date) => /* $date is a DateTime object */
);

$router->exceptionClassHandler(
    MyCustomException::class,
    fn(MyCustomException $e) => new HttpException(400, 'Bad request', $e)
);

// Specific status code
$router->addErrorResponseBuilder('404', function (HttpException $exception) {
    $response = new Response($exception->status);
    $response->setContent(new StringContent('Page not found'));
    return $response;
});

// Wildcard patterns
$router->addErrorResponseBuilder('40x', fn(HttpException $exception) => /* ... */);
$router->addErrorResponseBuilder('4xx', fn(HttpException $exception) => /* ... */);

// Default fallback
$router->addErrorResponseBuilder('default', fn(HttpException $exception) => /* ... */);

// API routes get JSON errors
$router->addErrorResponseBuilder(
    '404',
    function (HttpException $exception) {
        $response = new Response($exception->status);
        $response->setContent(new StringContent(
            json_encode(['error' => 'Not found'])
        ));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    },
    new PrefixMatcher('api/')
);

// Admin section gets themed error pages
$router->addErrorResponseBuilder(
    '403',
    fn(HttpException $exception) => renderAdminErrorPage($exception),
    new PrefixMatcher('admin/')
);

// Everything else gets default error pages
$router->addErrorResponseBuilder(
    '404',
    fn(HttpException $exception) => renderDefaultErrorPage($exception)
);

$router->addErrorResponseBuilder(
    '404',
    function (string $version, HttpException $exception) {
        return new Response(
            $exception->status,
            "API version {$version} endpoint not found"
        );
    },
    new PatternMatcher('api/:version')
);

// Try specialized handler first
$router->addErrorResponseBuilder(
    '404',
    function (HttpException $exception) {
        if (shouldUseCustomPage()) {
            return buildCustomPage($exception);
        }
        return null; // Fall back to next builder
    },
    priority: Priority::HIGH
);

// Fallback handler
$router->addErrorResponseBuilder(
    '404',
    fn(HttpException $exception) => buildDefaultPage($exception),
    priority: Priority::NORMAL
);

// Extract from a subdirectory
$router->routeExtractor(function (Request $request): string {
    $path = $request->url->path->__toString();
    return preg_replace('#^myapp/#', '', $path);
});