-
Notifications
You must be signed in to change notification settings - Fork 0
Routing
Routing is basically a way of assigning content to a request. When a user attempts to access a page or resource, this is where routing comes in to ensure the right content gets delivered to the end user.
On this page, I will talk you through how to set it up for your application using the Persona Clix Engine.
In your public index.php file, declare a use statement for the Router class at the top of the file below the main engine use statement.
use PersonaClix\Engine\Router;
You can now declare your routes. To keep things organised, I would recommend creating a standalone file for your routes, but you can keep them all in this file if you want to.
Register each route using a static function in the Router class called register(). It takes 3 parameters. The first parameter is the method of the request (GET or POST). The second parameter is the path for the route (/something). The third and final parameter is a callable action.
Here is an example of a registered route...
Router::register('GET', '/page', function() {
echo "Welcome.";
});
Inside your public index.php file, make sure you have required in the file containing your routes if you used a standalone file. This is not required if you just kept them in the index.php file.
Now you need to try to access the requested route. The easiest way is to use PHP's call_user_func() function and pass in the Router class's static method route(). It will call the callable action associated with the current route, or if the route cannot be found, will return nothing, so you might want to check if the action is callable before calling it.
Here is an example of this...
$route_action = Router::route();
if( is_callable( $route_action ) ) {
call_user_func( $route_action );
} else {
echo "Route cannot be found!";
}
That's about all you need to do for routing.