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
// 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->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);
});
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.