Dispatch Process
When thedispatch() method is called, the router performs the following steps:
- Extract Request Information: It captures the HTTP method (from
$_SERVER['REQUEST_METHOD']) and the URL path (from$_SERVER['REQUEST_URI']). - Find Matching Routes: It queries its associated
RouterCacheInterfaceto find all route definitions that match the current URL path using pre-compiled regular expressions. - Validate Method:
- If no routes match the path at all, a
NotFoundApivalkResponse(404) is returned. - If a path matches but the requested HTTP method is not supported for that path, a
MethodNotAllowedApivalkResponse(405) is returned.
- If no routes match the path at all, a
- Prepare Request and Controller:
- It identifies the
AbstractApivalkControllerclass associated with the matching route. - It identifies the corresponding
ApivalkRequestInterfaceclass. - It instantiates both, populating the request object with data from the route (including extracted path parameters).
- It identifies the
- Execute Middleware Pipeline: It hands off the request and controller instance to the
MiddlewareStackfor processing and final execution.
AbstractRouter
TheAbstractRouter provides the base functionality and dependency management for the router. It handles:
- Controller Factory: Manages the
ApivalkControllerFactoryInterfaceused to instantiate controllers. - Router Cache: Manages the
RouterCacheInterfaceused to retrieve route definitions. - Default Implementations: Provides a static
createDefault()method for quick bootstrapping with standard components.
Initialization
The router is typically initialized during the bootstrapping phase of the application:Router remains fast and focused on its single responsibility: dispatching requests.