Router

Component that stores routes and calls the associated controller methods

Router is defined at sirJuni\Framework\Handler\Router. This class is used to register routes of the application and also associate them with their controllers and corresponding methods. It is also used to register the error_handler which handles any routes which are not defined by the creator of the application. We can also put routes behind authentication by using middle-ware. All this and how to do it in code, you will learn below.

Creating Routes

To create routes we have to define them using Router::add_route method which takes 3 arguments.

<?php  // routes.php
require_once __DIR__ . "\\..\\vendor\\autoload.php";

use sirJuni\Framework\Handler\Router;

// add the controllers.php file here
require_once "controllers.php";

// add a route
Router::add_route('GET', '/user/Admin', [HomeController::class, 'index']);
?>

Breaking down the above function call to add_route ,

  • GET - It is the method of the request which the router will listen for this route.

  • /user/Admin - It is the path of the request.

  • [HomeController::class, 'index'] - This is an Array, the 0th element (HomeController::class]) is the Fully Qualified Class Name (FQCN) of the Controller class and the 1st element ('index') is the method of this controller that is responsible for handling this route.

If we want to also handle POST requests on the same route, we can simply add another route where the path is same, but instead of GET we will use POST.

Router::add_route('POST', '/user/Admin', [HomeController::class, 'create']);

Set Error Handler

We can set the error handler in the router, which is used to serve an error page when the route requested cannot be found.

We can set the error handler as follows

Router::set_error_handler(ErrorController::class, 'show');

The set_error_handler method takes 2 arguments, first one is the Controller classes FQCN and the second is the method of that class to serve the error.

The ErrorController should be defined as

// controllers.php
class ErrorController {
    public function show($request) {
        VIEW::init('error.html');      // render error.html
    }
}

Last updated