edit

Configuring Skytells Router

Skytells Router is a powerful routing system integrated with the Skytells PHP Framework.


Overview

In this tutorial we will learn step by step how to configure the routing system which used to resolve the controller's outputs.

Notice

If you do not have any idea about the configuration architecture
Please Click here to learn more about the architecture of the configurations.

Difficulty

  • For Seniors : Easy
  • For Beginners : Easy

MVC Diagram

If this is the first time using a Framework,
Lets understand how the router works first!

alt tag

The above diagram explains how MVC usually works.
Now lets move on ..


Router Configuration File

The Router settings file is located in the following path :
FILE PATH : Application/Misc/Config/Routes.php

1
2
3
4
Application
--[-] Misc
---- [-] Config
-------- * Routes.php < ------ ( Router Config )

Router Configurations

When opening the Application/Misc/Config/Routes.php file
You'll see the following PHP contents.

1
2
3
4
5
6
7
8
<?php
$Routes["CONFIG"]["DEFAULT_ROUTE_PARAM"] = "SYSCALLBACK";
$Routes["CONFIG"]["DEFAULT_CONTROLLER"] = "Home";
$Routes["CONFIG"]["DEFAULT_METHOD"] = "index";
$Routes["CONFIG"]["INIT_DEFALUT_METHOD_AUTOMATICALLY"] = TRUE;

Router::map('GET|POST', "/new_route", function() { Boot::Controller('Home', 'index', ['arg1', 'arg2']); });
Router::assign('/testAssignment', 'Home@index', ['arg1', 'arg2']);

As showing above,
The file contains an array ($Routes) and a few callable methods assigned to an static class named (Router) which controls everything in the MVC's ecosystem.

Lets explain first the definition of each array key stored in $Routes

1
2
3
4
5
<?php
$Routes["CONFIG"]["DEFAULT_ROUTE_PARAM"] = "SYSCALLBACK";
$Routes["CONFIG"]["DEFAULT_CONTROLLER"] = "Home";
$Routes["CONFIG"]["DEFAULT_METHOD"] = "index";
$Routes["CONFIG"]["INIT_DEFALUT_METHOD_AUTOMATICALLY"] = TRUE;
Name PURPOSE
DEFAULT_ROUTE_PARAM This array key is responsible for the default MVC callback, for example when you request to access localhost/home, the true request which transferred to the MVC's router will look this way (localhost/index.php?SYSCALLBACK=/home) so the value of this array key is the URI parameter which contains the routing path.
DEFAULT_CONTROLLER This array key is to identify the default controller for your home page.
DEFAULT_METHOD This array key is to identify the default controller method which will be executed upon initing each controller.
INIT_DEFALUT_METHOD_AUTOMATICALLY This array key is responsible for initing the default method DEFAULT_METHOD automatically without visiting the controller's default method.

Adding Routes

Now Lets explain whats the purpose of (Router) Class methods.

1
2
3
<?php
Router::map('GET|POST', "/new_route", function() { Boot::Controller('Home', 'index', ['arg1', 'arg2']); });
Router::assign('/testAssignment', 'Home@index', ['arg1', 'arg2']);
Name PURPOSE
map() This method is used for mapping routes and retrieving callbacks, its not requiring to mapping routes to an controller, so you can map your routes with your own callback function
assign() This method is used for mapping routes to an existing controller and retrieving callbacks

Mapping Routes

To map your routes, use the map() method. The following example maps all GET / requests.

1
2
<?php
Router::map( 'GET', '/', 'render_home', 'home' );

The map() method accepts the following parameters.

$method (string) This is a pipe-delimited string of the accepted HTTP requests methods.

Example: GET|POST|PATCH|PUT|DELETE

$route (string) This is the route pattern to match against. This can be a plain string, one of the predefined regex filters or a custom regex. Custom regexes must start with @.

Examples
Route Match Variables
/contact/ /contact/
/users/[i:id]/ /users/10/ $id: 10
/[a:c]/[a:a]?/[i:id]? /controller/action/21 $c: "controller", $a: "action", $id: 21

Booting up a Controller

1
2
3
4
5
6
7
8
9
<?php
// Booting up a controller using callback function
Router::map( 'GET', '/test/*', function($args) {
    Boot::Controller('Home', 'index', ['arg1', 'arg2']);
//                      ^        ^            ^
//                      |        |            |
//                 Controller  Method      Parameters ($args)    
});
// Now we've assined /test to boot the home controller.

OR Simply using the assign method.

1
2
3
4
5
6
<?php
// map users details page
Router::assign('/testAssignment', 'Home@index', ['arg1', 'arg2']);
//                      ^           ^      ^          ^
//                      |           |      |          |
//                     URI      Controller Method   Paramaters

For quickly adding multiple routes, you can use the addRoutes method.
This method accepts an array or any kind of traversable.

1
2
3
4
5
<?php
Router::addRoutes(array(
  array('PATCH','/users/[i:id]', 'users@update', 'update_user'),
  array('DELETE','/users/[i:id]', 'users@delete', 'delete_user')
));

Match Types

You can use the following limits on your named parameters. Skytells Router will create the correct regexes for you.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
*                    // Match all request URIs
[i]                  // Match an integer
[i:id]               // Match an integer as 'id'
[a:action]           // Match alphanumeric characters as 'action'
[h:key]              // Match hexadecimal characters as 'key'
[:action]            // Match anything up to the next / or end of the URI as 'action'
[create|edit:action] // Match either 'create' or 'edit' as 'action'
[*]                  // Catch all (lazy, stops at the next trailing slash)
[*:trailing]         // Catch all as 'trailing' (lazy)
[**:trailing]        // Catch all (possessive - will match the rest of the URI)
.[:format]?          // Match an optional parameter 'format' - a / or . before the block is also optional

The character before the colon (the 'match type') is a shortcut for one of the following regular expressions

1
2
3
4
5
6
'i'  => '[0-9]++'
'a'  => '[0-9A-Za-z]++'
'h'  => '[0-9A-Fa-f]++'
'*'  => '.+?'
'**' => '.++'
''   => '[^/\.]++'

You can register your own match types using the addMatchTypes() method.

1
2
<?php
Router::addMatchTypes(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?'));

Once your routes are all mapped you can start matching requests and continue processing the request.

Comment Routes

Did you know

You can add routes using just the code comments above your methods?

Of course yes, You can add your own routes just using the php comments.

alt tag

Overview

Say you have an exiting Controller contains some methods as mentioned below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php
 use Skytells\UI\View;
 use Skytells\Runtime;
 Class Home extends Controller implements \IController {

   /**
    * Some details about the method.
    * @method getUsers
    * @route /users
    */
   public function getUsers() {
     echo "Hello World";
   }
 }

Notice that the comments above method getUsers() contains @route string.
The string beside @route string will be used as the route destination.

Now lets using Skytells CLI to generate our routes.

Generating Routes

Open your Terminal and navigate it to the Framework or where you have installed the Framework.

Single Controller

Lets first generate routes for a single controller.

From your Terminal Window, Write the following command.

1
$ > php skytells make routes {CONTROLLER_NAME}

Replace {CONTROLLER_NAME} with the controller name which contains your methods.

Now notice that outputs for the command will be like :

1
2
$ > php skytells make routes {CONTROLLER_NAME}
$ > Routing [getUsers] to http://localhost/users [OK]

In Addition:
You'll notice that a new file (Autoroutes.php) will be created in Application/Misc/Config dir.

This file contains all generated routes.

Now what if the method containing an arguments ? Of course the system will be able to handle those arguments if you've passed them through the PHP comments written above the method.

For Example : Say we have this method :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
 use Skytells\UI\View;
 use Skytells\Runtime;
 Class Home extends Controller implements \IController {

   /**
    * Some details about the method.
    * @method getUsers
    * @route /users
    * @arguments ['id' => 1, 'name' => 'Hazem']
    */
   public function getUsers($id, $name) {
     echo "Hello World";
   }
 }

Notice that the comments above method getUsers() contains @route string.
And @arguments contains an array.
This array is your arguments which will be passed to the routing system.
The string beside @route string will be used as the route destination.

Now lets perform the same command on CLI :

1
$ > php skytells make routes {CONTROLLER_NAME}

Now the (Autoroutes.php) file should contains the routes with methods requires some arguments.

All Controllers

If want to generate routes for all workspace controllers
Perform the following command.

1
$ > php skytells make routes all

Notice that we now wrote all rather than writing the controller name.

Now the system will perform routes generation across all of your controllers.

Regenerate Routes

Everytime you run auto-gen command,
The system will not overwriting your existing routes in (Autoroutes.php) routing file.

If you wanna overwriting the exiting routes and start over just add --regen
As an option for your command to be like the following example.

1
$ > php skytells make routes all --regen

Now the system will overwriting your existing routes and reroute all your controllers 's methods.