Skip to content

Routing

The routing mechanism is responsible for directing incoming HTTP requests to their corresponding handlers, which can either be closures or controller methods.

Defining Routes

Routes are defined using the methods provided by the $route instance. Each route consists of a URL pattern and a corresponding handler, which can be either a closure or a controller method.

Closure Handler Example

php
$route->get('/hello/{name}', function(ServerRequest $request, RequestArguments $args)
{
    $name = $args->name;
    return "Hello {$name}";
});

In this example, the closure takes a ServerRequest object and an array of route parameters ($args) as arguments. It extracts the value of the name parameter from the $args array and returns a personalized greeting message.

Controller Handler Example

php
$route->get('/hello/{name}', [HelloController::class, 'hello']);

In this example, the route handler is a controller method defined in the HelloController class. The hello method is responsible for processing the request and returning the response.

Request Handling

When an incoming HTTP request matches a defined route, the corresponding handler is invoked. The handler is executed with the following arguments:

  • Closures: The closure is executed directly with the ServerRequest object and route parameters.
  • Controller Methods: The controller method is called with the appropriate arguments, allowing for a more structured approach to request handling.

By using the routing mechanism, you can decouple URL logic from the rest of the application, making it easier to maintain and test.

Released under the MIT License.