# Router

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
<?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`.

```php
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

```php
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

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shoaib-1.gitbook.io/sirjuni/router.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
