Skip to content

New Route

John Aldrich Bernardo edited this page Feb 18, 2018 · 3 revisions

Creating and registering a new route

<?php

require("./vendor/autoload.php");

use \Calf\HTTP\Router as Router;
use \Calf\HTTP\Route as Route;
use \Calf\HTTP\Request as Request;
use \Calf\HTTP\Response as Response;

$router = new Router();

$home = new Route('/', function(Request $req, Response $res, array $args) {
    return $res->set('Hello World');
});

$router->add($home);

$response = $router->dispatch();
$response->render();

Pretty URL

<?php

require("./vendor/autoload.php");

use \Calf\HTTP\Router as Router;
use \Calf\HTTP\Route as Route;
use \Calf\HTTP\Request as Request;
use \Calf\HTTP\Response as Response;

$router = new Router();

$home = new Route('/{name}', function(Request $req, Response $res, array $args) {
    return $res->set('Hi, ' . $args['name']);
});

$router->add($home);

$response = $router->dispatch();
$response->render();

Run above example into PHP build-it Web Server

php -S localhost:8080 index.php

Visit localhost:8080/John

Example will output:

Hi, John

Patterns

Calf Routing allows you to use regular expression for creating route

Defining Route

<?php

$get = new Route('/get/{key:pattern}',...

?>

Example

<?php

$get = new Route('/get/{product:\w+}/{count:\d+}', ...

?>

Clone this wiki locally