Skip to content

Routing

Persona Clix edited this page May 16, 2018 · 7 revisions

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.

Step 1

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;

Step 2

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 4 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 parameter is a callable action, and the fourth and final parameter is an optional array with additional options for the route.

Standard Registered Routes

These are routes with just the minimum information required to make them work.

Here is an example of a standard registered route...

Router::register('GET', '/page',
	function() {
		echo "Welcome.";
	}
);

Registered Routes with Additional Options

These are routes that have additional options specified, usually to be more restrictive in when the route comes into effect.

Currently there is only one additional option available, and that is the host option. When specified, the route will only apply if the requested hostname matches the one registered with the route. This can be good if you wish to use the one application across multiple domains or subdomains.

Here is an example of a registered route with a specified hostname.

Router::register('GET', '/',
	function() {
		echo "Welcome to example.com!";
	},
	[
		'host' => 'www.example.com'
	]
);

Accessing Your Routes

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.

Clone this wiki locally