Router
class Router implements BindingRegistrar, Registrar mixin RouteRegistrar
Traits
Constants
| private CURRENT_ROUTE_CONTEXT_KEY |
|
| private CURRENT_REQUEST_CONTEXT_KEY |
|
Properties
| static protected array | $macros | The registered string macros. |
from Macroable |
| protected Dispatcher | $events | The event dispatcher instance. |
|
| protected Container | $container | The IoC container instance. |
|
| protected RouteCollectionInterface | $routes | The route collection instance. |
|
| protected array<string, string> | $middleware | All of the short-hand keys for middlewares. |
|
| protected array<string, array<int, string>> | $middlewareGroups | All of the middleware groups. |
|
| array<int, string> | $middlewarePriority | The priority-sorted list of middleware. |
|
| protected Closure> | $binders | The registered route value binders. |
|
| protected array<string, string> | $patterns | The globally available parameter patterns. |
|
| protected array | $groupStack | The route group attribute stack. |
|
| protected Closure|array|null | $implicitBindingCallback | The registered custom implicit binding callback. |
|
| static array<int, string> | $verbs | All of the verbs supported by the router. |
Methods
Mix another object into the class.
Dynamically handle calls to the class.
Dynamically handle calls into the router instance.
Call the given Closure with this instance then return the instance.
Register a new GET route with the router.
Register a new POST route with the router.
Register a new PUT route with the router.
Register a new PATCH route with the router.
Register a new DELETE route with the router.
Register a new OPTIONS route with the router.
Register a new route responding to all verbs.
Create a redirect from one URI to another.
Create a permanent redirect from one URI to another.
Register a new route that returns a view.
Register a new route with the given verbs.
Register an array of resource controllers.
Register an array of resource controllers that can be soft deleted.
Route a resource to a controller.
Register an array of API resource controllers.
Route an API resource to a controller.
Register an array of singleton resource controllers.
Route a singleton resource to a controller.
Register an array of API singleton resource controllers.
Route an API singleton resource to a controller.
Update the group stack with the given attributes.
Merge the given array with the last group stack.
Get the prefix from the last group on the stack.
Add a route to the underlying route collection.
Create a new route instance.
Determine if the action is routing to a controller.
Add a controller based route action to the action array.
Prepend the last group namespace onto the use clause.
Prepend the last group controller onto the use clause.
Prefix the given URI with the last prefix.
Add the necessary where clauses to the route based on its initial registration.
Return the response returned by the given route.
Match a route, run middleware, and call the given callback instead of the controller.
Run the given route within a Stack "onion" instance.
Create the middleware pipeline used to dispatch a route.
Gather the middleware for the given route with resolved class names.
Resolve a flat array of middleware classes from the provided array.
Substitute the implicit route bindings for the given route.
Register a callback to run after implicit bindings are substituted.
Call the binding callback for the given key.
Register a route matched event listener.
Get all of the defined middleware short-hand names.
Check if a middlewareGroup with the given name exists.
Get all of the defined middleware groups.
Register a group of middleware.
Add a middleware to the beginning of a middleware group.
Add a middleware to the end of a middleware group.
Remove the given middleware from the specified group.
Flush the router's middleware groups.
Add a new route parameter binder.
Get the binding callback for a given binding.
Get the global "where" patterns.
Set a global where pattern on all routes.
Set a group of global where patterns on all routes.
Determine if the router currently has a group stack.
Get the current group stack for the router.
Get a route parameter for the current route.
Get the request currently being dispatched.
Get the currently dispatched route instance.
Check if a route with the given name exists.
Get the current route name.
Alias for the "currentRouteNamed" method.
Determine if the current route matches a pattern.
Get the current route action.
Alias for the "currentRouteUses" method.
Determine if the current route action matches a given action.
Set the unmapped global resource parameters to singular.
Set the global resource parameter mapping.
Get or set the verbs used in the resource URIs.
Get the underlying route collection.
Set the compiled route collection instance.
Determine whether this router owns the application's global route state.
Flush all static routing caches.
Compile routes and pre-warm collection and static caches.
Pre-warm all caches for the registered routes.
Remove any duplicate middleware from the given array.
Flush all static state.
Details
in
Macroable at line 28
static void
macro(string $name, callable|object $macro)
Register a custom macro.
Boot-only. Macros persist in a static property for the worker lifetime and apply to every subsequent call on the macroable class.
in
Macroable at line 41
static void
mixin(object $mixin, bool $replace = true)
Mix another object into the class.
Boot-only. Delegates to macro() for each method; registered macros persist in a static property for the worker lifetime.
in
Macroable at line 57
static bool
hasMacro(string $name)
Check if macro is registered.
in
Macroable at line 68
static void
flushMacros()
Flush the existing macros.
Boot or tests only. Clears worker-wide macros; concurrent coroutines may resolve different methods depending on timing.
in
Macroable at line 78
static mixed
__callStatic(string $method, array $parameters)
Dynamically handle calls to the class.
at line 1460
mixed
__call(string $method, array $parameters)
Dynamically handle calls into the router instance.
in
Tappable at line 15
mixed
tap(callable|null $callback = null)
Call the given Closure with this instance then return the instance.
at line 125
__construct(Dispatcher $events, Container|null $container = null)
Create a new Router instance.
at line 135
Route
get(string $uri, array|string|callable $action = null)
Register a new GET route with the router.
at line 143
Route
post(string $uri, array|string|callable $action = null)
Register a new POST route with the router.
at line 151
Route
put(string $uri, array|string|callable $action = null)
Register a new PUT route with the router.
at line 159
Route
patch(string $uri, array|string|callable $action = null)
Register a new PATCH route with the router.
at line 167
Route
delete(string $uri, array|string|callable $action = null)
Register a new DELETE route with the router.
at line 175
Route
options(string $uri, array|string|callable $action = null)
Register a new OPTIONS route with the router.
at line 183
Route
any(string $uri, array|string|callable|null $action = null)
Register a new route responding to all verbs.
at line 191
Route
fallback(array|string|callable|null $action)
Register a new fallback route with the router.
at line 205
Route
redirect(string $uri, string $destination, int $status = 302)
Create a redirect from one URI to another.
at line 215
Route
permanentRedirect(string $uri, string $destination)
Create a permanent redirect from one URI to another.
at line 223
Route
view(string $uri, string $view, array $data = [], int|array $status = 200, array $headers = [])
Register a new route that returns a view.
at line 237
Route
match(array|string $methods, string $uri, array|string|callable $action = null)
Register a new route with the given verbs.
at line 245
void
resources(array $resources, array $options = [])
Register an array of resource controllers.
at line 255
void
softDeletableResources(array $resources, array $options = [])
Register an array of resource controllers that can be soft deleted.
at line 265
PendingResourceRegistration
resource(string $name, string $controller, array $options = [])
Route a resource to a controller.
at line 284
void
apiResources(array $resources, array $options = [])
Register an array of API resource controllers.
at line 294
PendingResourceRegistration
apiResource(string $name, string $controller, array $options = [])
Route an API resource to a controller.
at line 310
void
singletons(array $singletons, array $options = [])
Register an array of singleton resource controllers.
at line 320
PendingSingletonResourceRegistration
singleton(string $name, string $controller, array $options = [])
Route a singleton resource to a controller.
at line 339
void
apiSingletons(array $singletons, array $options = [])
Register an array of API singleton resource controllers.
at line 349
PendingSingletonResourceRegistration
apiSingleton(string $name, string $controller, array $options = [])
Route an API singleton resource to a controller.
at line 367
Registrar
group(array $attributes, Closure|array|string $routes)
Create a route group with shared attributes.
at line 388
protected void
updateGroupStack(array $attributes)
Update the group stack with the given attributes.
at line 400
array
mergeWithLastGroup(array $new, bool $prependExistingPrefix = true)
Merge the given array with the last group stack.
at line 408
protected void
loadRoutes(Closure|string $routes)
Load the provided routes.
at line 420
string
getLastGroupPrefix()
Get the prefix from the last group on the stack.
at line 434
Route
addRoute(array|string $methods, string $uri, array|string|callable|null $action)
Add a route to the underlying route collection.
at line 442
protected Route
createRoute(array|string $methods, string $uri, mixed $action)
Create a new route instance.
at line 472
protected bool
actionReferencesController(mixed $action)
Determine if the action is routing to a controller.
at line 485
protected array
convertToControllerAction(array|string $action)
Add a controller based route action to the action array.
at line 510
protected string
prependGroupNamespace(string $class)
Prepend the last group namespace onto the use clause.
at line 522
protected string
prependGroupController(string $class)
Prepend the last group controller onto the use clause.
at line 544
Route
newRoute(array|string $methods, string $uri, mixed $action)
Create a new Route object.
at line 554
protected string
prefix(string $uri)
Prefix the given URI with the last prefix.
at line 562
protected Route
addWhereClausesToRoute(Route $route)
Add the necessary where clauses to the route based on its initial registration.
at line 575
protected void
mergeGroupAttributesIntoRoute(Route $route)
Merge the group stack with the controller action.
at line 586
Response
respondWithRoute(string $name)
Return the response returned by the given route.
at line 598
Response
dispatch(Request $request)
Dispatch the request to the application.
at line 608
Response
dispatchToRoute(Request $request)
Dispatch the request to a route and return the response.
at line 623
Response
dispatchToCallback(Request $request, Closure $callback)
Match a route, run middleware, and call the given callback instead of the controller.
Performs the full route context lifecycle (route matching, context setup, route resolver, RouteMatched event, middleware pipeline) but calls the provided callback as the terminal handler instead of the route's action.
Used by the WebSocket server for handshake requests where route matching and middleware must run but the controller must not be invoked.
at line 665
protected Response
runRoute(Request $request, Route $route)
Return the response for the given route.
at line 682
protected mixed
runRouteWithinStack(Route $route, Request $request)
Run the given route within a Stack "onion" instance.
at line 701
protected Pipeline
newPipeline()
Create the middleware pipeline used to dispatch a route.
at line 711
protected array
middlewareFor(Route $route)
Resolve middleware for one route dispatch.
at line 724
array
gatherRouteMiddleware(Route $route)
Gather the middleware for the given route with resolved class names.
at line 737
array
resolveMiddleware(array $middleware, array $excluded = [])
Resolve a flat array of middleware classes from the provided array.
at line 782
protected array
sortMiddleware(Collection $middlewares)
Sort the given middleware by priority.
at line 790
Response
prepareResponse(Request $request, mixed $response)
Create a response instance from the given value.
at line 808
static Response
toResponse(Request $request, mixed $response)
Static version of prepareResponse.
at line 862
mixed
substituteImplicitBindings(Route $route)
Substitute the implicit route bindings for the given route.
at line 879
Router
substituteImplicitBindingsUsing(callable $callback)
Register a callback to run after implicit bindings are substituted.
at line 891
protected mixed
performBinding(string $key, string $value, Route $route)
Call the binding callback for the given key.
at line 899
void
matched(string|callable $callback)
Register a route matched event listener.
at line 909
array
getMiddleware()
Get all of the defined middleware short-hand names.
at line 922
Router
aliasMiddleware(string $name, string|Closure $class)
Register a short-hand name for a middleware.
Boot-only. The alias persists in the singleton Router for the worker lifetime and applies to every subsequent route resolution.
at line 932
bool
hasMiddlewareGroup(string $name)
Check if a middlewareGroup with the given name exists.
at line 942
array
getMiddlewareGroups()
Get all of the defined middleware groups.
at line 955
Router
middlewareGroup(string $name, array $middleware)
Register a group of middleware.
Boot-only. The middleware group persists in the singleton Router for the worker lifetime and applies to every subsequent route resolution.
at line 972
Router
prependMiddlewareToGroup(string $group, string $middleware)
Add a middleware to the beginning of a middleware group.
If the middleware is already in the group, it will not be added again.
Boot-only. The middleware group persists in the singleton Router for the worker lifetime and applies to every subsequent route resolution.
at line 991
Router
pushMiddlewareToGroup(string $group, string $middleware)
Add a middleware to the end of a middleware group.
If the middleware is already in the group, it will not be added again.
Boot-only. The middleware group persists in the singleton Router for the worker lifetime and applies to every subsequent route resolution.
at line 1009
Router
removeMiddlewareFromGroup(string $group, string|array $middleware)
Remove the given middleware from the specified group.
at line 1039
Router
flushMiddlewareGroups()
Flush the router's middleware groups.
Boot or tests only. Clears the singleton Router's middleware-group registry shared by every coroutine; concurrent requests lose middleware mid-dispatch.
at line 1052
void
bind(string $key, string|callable $binder)
Add a new route parameter binder.
Boot-only. The binder persists in the singleton Router for the worker lifetime and runs on every subsequent route parameter resolution.
at line 1066
void
model(string $key, string $class, Closure|null $callback = null)
Register a model binder for a wildcard.
Boot-only. The model binder persists in the singleton Router for the worker lifetime and runs on every subsequent route parameter resolution.
at line 1074
Closure|null
getBindingCallback(string $key)
Get the binding callback for a given binding.
at line 1088
array
getPatterns()
Get the global "where" patterns.
at line 1099
void
pattern(string $key, string $pattern)
Set a global where pattern on all routes.
Boot-only. The pattern persists in the singleton Router for the worker lifetime and applies to every subsequent route definition.
at line 1110
void
patterns(array $patterns)
Set a group of global where patterns on all routes.
Boot-only. The patterns persist in the singleton Router for the worker lifetime and apply to every subsequent route definition.
at line 1120
bool
hasGroupStack()
Determine if the router currently has a group stack.
at line 1128
array
getGroupStack()
Get the current group stack for the router.
at line 1136
mixed
input(string $key, string|null $default = null)
Get a route parameter for the current route.
at line 1144
Request|null
getCurrentRequest()
Get the request currently being dispatched.
at line 1152
Route|null
getCurrentRoute()
Get the currently dispatched route instance.
at line 1160
Route|null
current()
Get the currently dispatched route instance.
at line 1168
bool
has(string|array $name)
Check if a route with the given name exists.
at line 1184
string|null
currentRouteName()
Get the current route name.
at line 1192
bool
is(mixed ...$patterns)
Alias for the "currentRouteNamed" method.
at line 1200
bool
currentRouteNamed(mixed ...$patterns)
Determine if the current route matches a pattern.
at line 1208
string|null
currentRouteAction()
Get the current route action.
at line 1220
bool
uses(array|string ...$patterns)
Alias for the "currentRouteUses" method.
at line 1234
bool
currentRouteUses(string $action)
Determine if the current route action matches a given action.
at line 1245
void
singularResourceParameters(bool $singular = true)
Set the unmapped global resource parameters to singular.
Boot-only. Delegates to ResourceRegistrar::singularParameters() which persists in a static property for the worker lifetime.
at line 1253
void
resourceParameters(array $parameters = [])
Set the global resource parameter mapping.
at line 1261
array|null
resourceVerbs(array $verbs = [])
Get or set the verbs used in the resource URIs.
at line 1269
RouteCollectionInterface
getRoutes()
Get the underlying route collection.
at line 1277
void
setRoutes(RouteCollection $routes)
Set the route collection instance.
at line 1301
void
setCompiledRoutes(array $routes)
Set the compiled route collection instance.
Boot-only. Replaces the singleton Router's route collection and rebinds the container's 'routes' instance; runtime use breaks every concurrent request mid-dispatch.
at line 1319
protected bool
ownsGlobalRouteState()
Determine whether this router owns the application's global route state.
at line 1330
protected void
flushRoutingCaches()
Flush all static routing caches.
Called when the route collection is replaced to clear stale data. In Swoole workers live forever, so stale statics would persist.
at line 1354
void
compileAndWarm()
Compile routes and pre-warm collection and static caches.
In dev mode, compiles RouteCollection → CompiledRouteCollection for CompiledUrlMatcher performance (O(1) hash + single regex). In production with route:cache, routes are already CompiledRouteCollection — compile is skipped and only warmUp() runs.
Called from HttpServer\Server and WebSocketServer\Server after Kernel::bootstrap() returns, before $server->start(). Idempotent — safe to call from both servers in combined setups.
Boot-only. Replaces the route collection and populates process-wide caches before fork.
at line 1372
void
warmUp()
Pre-warm all caches for the registered routes.
Eagerly populates route compilation, middleware resolution, and reflection caches so they're available before fork. Workers inherit via copy-on-write in both SWOOLE_PROCESS and SWOOLE_BASE modes.
at line 1417
static array
uniqueMiddleware(array $middleware)
Remove any duplicate middleware from the given array.
at line 1442
Router
setContainer(Container $container)
Set the container instance used by the router.
Tests only. Swaps the singleton Router's container reference; per-request use races across coroutines and breaks every concurrent route dispatch.
at line 1452
static void
flushState()
Flush all static state.