Skip to content

New Route

John Aldrich Bernardo edited this page Jan 28, 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);

$router->dispatch();

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);

$router->dispatch();

Run above example into PHP build-it Web Server

php -S localhost:8080 index.php

Visit localhost:8080/John

Example will output:

Hi, John

Clone this wiki locally