Download the PHP package joby/smol-router without Composer
On this page you can find all versions of the php package joby/smol-router. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download joby/smol-router
More information about joby/smol-router
Files in joby/smol-router
Package smol-router
Short Description A straightforward and unopinionated router for human-scale applications.
License MIT
Informations about the package smol-router
smolRouter
A lightweight PHP router with flexible matching strategies and automatic parameter injection.
Installation
About
This router uses smolRequest for handling HTTP requests and smolResponse for building responses. Route handlers receive Request objects and return Response objects from these libraries.
Basic Usage
Adding new routes with the Router::add() method will make them available for both GET and POST requests.
Route Normalization
The default normalizer strips leading slashes, but not trailing slashes. So /foo/bar is the same as foo/bar but is not the same as /foo/bar/. The root is returned as an empty string.
This is very specific, but is actually important to making the paths here easily interoperable with retrieving files via smolFS.
Request methods
Routes can be limited to common request methods using Router::get(), Router::post(), etc.
You can also specify your own list of request methods via Router::add() by passing values from the Method enum.
Matchers
ExactMatcher
Matches a specific path exactly.
PatternMatcher
Matches paths with named parameters.
CatchallMatcher
Matches any path.
PrefixMatcher
Matches any path starting with a prefix. By default, captures the remainder after the prefix as prefix_remainder.
PrefixPatternMatcher
Matches paths starting with a pattern containing named parameters. By default, captures the remainder after the pattern as prefix_remainder.
SuffixMatcher
Matches paths ending with a suffix. By default, captures the base path before the suffix as suffix_base.
SuffixPatternMatcher
Matches paths ending with a pattern containing named parameters. By default, captures the base path before the pattern as suffix_remainder.
TransformerMatcher
Transforms a path before matching it against a child matcher. This is useful for preprocessing paths (e.g., lowercasing for case-insensitive matching, normalizing formats, removing query strings). By default, captures the original untransformed path as original_path.
The transformer function can also reject a match by returning null.
Composing Matchers
Matchers can be composed together using the with() method to build complex matching patterns. Composable matchers accept a child matcher that will be evaluated against a transformed portion of the path.
Basic Composition
Compose two matchers to combine their functionality:
Nested Composition
Chain multiple matchers for complex patterns:
Reusable Compositions
Define matchers once and compose them multiple times:
Combining Different Matchers
Mix various matcher types to build sophisticated routing patterns:
Parameter Injection
Handler functions automatically receive parameters extracted by matchers, with type conversion. If a type cannot be created from the string form of the parameter an exception will be thrown, and the user will get a 400 error indicating that it was an invalid request.
If you write your own Matchers, you can provide parameters in the MatchedRoute object in any type you like, and they will be injected to the handler by name.
HTTP Methods
Restrict routes to specific HTTP methods. By default all routes can match both GET and POST requests.
Priorities
Control route matching order with priorities. By default routes are added with "normal" priority.
Guards
Guards provide access control that runs before route handlers. They're evaluated in priority order and can allow, deny, or defer the decision to continue processing.
Guard Return Values
null- Continue processing (allow access if no other guards deny)false- Deny access immediately (returns 403 Forbidden)true- Allow access immediately (skip remaining guards)
Guard HTTP Method Filtering
By default guards run on all HTTP methods, but can be limited to specific methods:
Guard Priority
Guards are executed in priority order (HIGH → NORMAL → LOW). Processing stops at the first non-null return value.
Response Modifiers
Modifiers alter responses after they're generated by route handlers. They run in priority order and can modify any response, including error pages. They can also have matcher results injected the same as route handlers.
Modifier Return Values
null- Keep the original response unchangedResponse- Replace the response with the returned oneFinalResponse- Replace the response and skip all remaining modifiers
Modifier Execution
Modifiers run in priority order (HIGH → NORMAL → LOW) and unless a FinalResponse is returned all of them will be run:
Modifier HTTP Method Filtering
By default modifiers run on all HTTP methods, but can be limited to specific methods:
When Modifiers Run
Modifiers execute for:
- Successful route matches (200, 201, etc.)
- Error responses (404, 500, etc.)
- Any response generated by the router
Modifiers do not run when:
- A handler returns a
FinalResponse - A higher-priority modifier returns a
FinalResponse - An exception is thrown during path extraction or normalization
Type Handlers
Register custom type handlers for parameter conversion.
Error Handling
Exception Handlers
Convert exceptions into HTTP errors by type. A handful of defaults are provided that will convert most exceptions into either 400 or 500 responses.
Error Page Builders
Customize error responses by status code and route. Builders are evaluated by specificity first (specific codes before wildcards), then by priority within each level.
Route-Specific Error Pages
Use matchers to customize error pages for different sections of your site:
Parameter Injection
Error page builders support parameter injection from matchers:
Priority and Fallback
Control evaluation order with priorities, and return null to try the next builder:
Evaluation Order
- Specificity: Specific codes ("404") before patterns ("40x" → "4xx" → "default")
- Priority: Within each specificity level, HIGH → NORMAL → LOW
- Fallback: If a builder returns
null, try the next one
Route Extraction
Customize how routes are extracted from requests. By default the path used for routing is the full path string from the request's URL object.
TinyRouter
There is also a more stripped-down version available, called TinyRouter that can be used in cases where the full router class is too opinionated. TinyRouter does not support guards, modifiers, exception handlers, or exception response building. It simply returns null from run() if no Response was generated, and does not do any of its own exception handling.
TinyRouter also does not support FinalResponse skipping, as it will always return the first Response a handler produces.
Requirements
Fully tested on PHP 8.3+, static analysis for PHP 8.1+.
License
MIT License - See LICENSE file for details.