Skip to content

ch02_routing

Daniel Samson edited this page Jul 6, 2022 · 13 revisions

TeensyPHP provides a very lightweight and simple router to manage the endpoints of your application. You can specify the endpoints using the route function, which accepts two predicates and a callback function.

route(bool $method, bool $path, callable $action)

HTTP Verb/Method filtering

TeensyPHP provides the method predicate to assist you in filtering the HTTP method from the client request.

method(string $method)

You can choose to use the pre-defined constants:

method(GET);
method(POST);
method(PUT);
method(PATCH);
method(DELETE);
method(HEAD);
method(CONNECT);
method(OPTIONS);
method(TRACE);

URL filtering

TeensyPHP provides the url_path predicate for simple urls:

url_path("/contact-us")

and url_path_params for urls with parameters:

url_path_params('/orders/from/:from_date/to/:to_date')

the parameters follow the /:param_name pattern, which you can access via the $_GET super global.

$from_date = $_GET[':from_date'];
$to_date = $_GET[':to_date'];

Single Action Controller

TeensyPHP has the concept of callable actions to handle the endpoints of your application:

route(method(GET), url_path('/contact-us'), function() {
    // do something
});