Erstwhile has two ways of defining an application’s routing behavior:
- The default method, which creates routes automatically based on naming conventions.
- The explicit method, where a developer overrides the
ErstwhileController‘sgetRoutes()method and explicitly lays out which paths point to which actions in a given controller.
Erstwhile currently builds the application’s routing table at compilation time, but we are investigating of how to update it within a running application. That will likely be added in a future release.
Default Method
By default Erstwhile will build the application’s routing table by iterating through your controllers and building routes for each method that has a name ending in Action. For example, if the website visitor goes to the path /automobiles/view/1234, they would see the output of the AutomobileController‘s method viewAction, with an argument of { "id": "1234" }
If you’d like to use a different base path for a given controller (to have AutomobileController base its paths off of /car rather than /automobile, for example) you can override the getControllerPath() method in the controller.
There are a few special cases to be aware of:
- A controller called
IndexControllerwill not have a path. If it has an action calledloginAction(), for example, that route would be/loginrather than/index/login - An action called
indexActionwill listen at the root of a controller. IfPathControllerhas anindexAction, the route would be/pathrather than/path/index. Similarly, the overall root route is defined inIndexController‘sindexActionmethod. - By default, the 3rd item in a path is passed in as an argument called
id. If you need multiple wildcard items, it’s time to look at explicit routing.
Explicit Method
If you require more fine-grained control over routing, you can override the ErstwhileController‘s getRoutes() method and have it return an explicit routing table for the controller.
For example, if that method returns this:
{
"/login": {
"action": "login"
},
"/cars/view/:id/:englishname": {
"action": "view"
}
}There would be two routes defined for this controller.
Some caveats to be aware of:
- Each wildcard specified in a route is passed in by name to the action’s
argsparameter. - Specifying explicit routes means the default behavior is abandoned altogether. The default routes will not be created.
- The developer can define routes for any path, even some which conflict with other controllers. In this example, if the
IndexContollerhad aloginAction, it is undefined what the routing table would look like. Be careful to avoid conflicts.