Menu

Simple Routing
Creating and handling routes

Overview

Understanding Routing

As explained before, Leaf uses a single root file, to which all the server requests are redirected. Leaf then takes these requests and matches them to rules you have defined. The results are then displayed to the user. It's actually a very simple concept.

In order to use Leaf's router in your project, you have to imoprt it

$leaf = new Leaf\Core\Leaf();

Using a different router

Leaf uses a router based on the Leaf's Core router component as for it's core, but this is seperated from the rest of Leaf itself, so, you can tie in any routing library of your choice.

1. Install it
composer require .../whatever-router
2. Import it into your project
$app = new WhatEver\Router(); // you can still use Leaf modules $response = new Leaf\Core\Response();

Creating Routes

You can define application routes using proxy methods on the Leaf\Core\Leaf instance. Leaf supports a whole bunch of HTTP methods, see all supported methods.

GET requests

You can add a route that handles only GET HTTP requests with the Leaf router's get() method. It accepts two arguments:

$leaf->get('/home', function() { // your code });

POST requests

You can add a route that handles only POST HTTP requests with the Leaf router's post() method. It accepts two arguments:

$leaf->post('/users/add', function() use($request) { $user = $request->getParam('user'); // create a new user });
Using Post Params
View Request for more info on handling params

PUT requests

You can add a route that handles only PUT HTTP requests with the Leaf router’s put() method. It accepts two arguments:

$leaf->put('/book/edit/{id}', function($id) { // your code });

DELETE requests

You can add a route that handles only DELETE HTTP requests with the Leaf router's delete() method. It accepts two arguments:

$leaf->delete('/quotes/{id}', function($id) { // delete quote });

OPTIONS requests

You can add a route that handles only OPTIONS HTTP requests with the Leaf router's options() method. It accepts two arguments:

$leaf->options('/quotes/{id}', function($id) { // return headers });

PATCH requests

You can add a route that handles only PATCH HTTP requests with the Leaf router's patch() method. It accepts two arguments:

$leaf->patch('/post/{id}', function($id) { // your code });

ALL requests

You can add a route that handles all HTTP requests with the Leaf router's all() method. It accepts two arguments:

$leaf->all('/post/{id}', function($id) { // your code });

Route "Hooking"

You can add a route that handles a couple of HTTP methods with the Leaf router's match() method. It accepts three arguments:

$leaf->match('GET|POST', '/people', function() { // your code });

Running your routes

After setting all the routes, you'll need to dispatch the routes. This is achieved through Leaf's run() method.

$leaf->run();

Next Steps

Request
Response
Named Parameters
Handling 404