Routes HTTP requests to your code.
As HTTP requests are received by an application, the appropriate logic methods need to be called, along with certain files being loaded to construct the correct view for the request. This is done by taking the HTTP request and routing it to the matching areas of the application source code.
This repository breaks down the concept of routing into three areas of responsibility:
- Matching an HTTP request to an appropriate callback function.
- Creating an Assembly of logic and view files that match the request.
- Processing the Assemblies, in order to create the correct HTTP response.
When referring to Requests within this repository, we are always referring to a PSR-7 HTTP Message.
- Your application can have a
router.phpin project root, but is completely optional due to
router.default.phpbeing provided by WebEngine. You can use the router.php file to add complicated rules that define which source files are used to build up the response, rather than always being limited to using path-based rules, as is currently the case with WebEngine.
- The name of the application's router is defined in config by
- The application router defines a class called
Routerin the application's root namespace, which extends
go()method is called, supplying a PSR-7
RequestInterfacewhich will call functions of the application's router.
- The application router can have any number of functions. They are made "routable" by adding an Attribute that extends
Route. Available Attributes include
Post(and other HTTP verbs) or
Anyto match on all verbs.
- The simplest routable function has the Any attribute with no parameters (
#[Any()]), which will be executed for every request.
- Available Attribute parameters include:
nameto provide the route a name for future reference,
acceptto provide a Content-type to match the Request's
pathto define a matching path (with pattern matching),
functionto define the function to call.
- Only the functions that have Attributes that match the incoming request will be executed.
- It's the job of the application's routable functions to add appropriate view and logic files to the Router's
Assemblyobjects. The framework (WebEngine in my case) will then use the Assembly objects to build up the appropriate
Viewand execute the appropriate
Logicobjects in the correct order.
- Perform content negotiation when there are multiple matches. For example: an API route might explicitly accept "application/xml" but the default accept header of web browsers also sends this for page requests, but it gives it a q=0.9 - as long as there is a route with text/html or application/xhtml+xml with a higher q value, it should be preferred.
- Take a RequestInterface and a project directory, and construct the appropriate Assembly objects - matching the URL path to directory paths, extracting dynamic paths where appropriate.