Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/MonishAMPT/fastroute-code/llms.txt

Use this file to discover all available pages before exploring further.

Route handlers are the functions or methods that execute when a route is matched. FastRoute supports multiple handler types, giving you flexibility in how you organize your code.

Handler Types

FastRoute supports three main types of handlers:
  1. Function-based handlers - Simple functions defined in your main file
  2. Class-based handlers - Methods from instantiated classes
  3. Inline closures - Anonymous functions defined directly in routes

Function-Based Handlers

Function-based handlers are simple PHP functions that are called when a route matches.

Defining Function Handlers

index.php
function test_get() {
    echo json_encode(["message" => "This is the test route (GET)"]);
}

function test_post() {
    $data = json_decode(file_get_contents('php://input'), true);
    echo json_encode(["message" => "POST request received", "data" => json_encode($data)]);
}

function items_get() {
    echo json_encode(["items" => ["item1", "item2", "item3"]]);
}

function items_post() {
    $data = json_decode(file_get_contents('php://input'), true);
    echo json_encode(["message" => "Item created", "item" => $data]);
}

Using Function Handlers in Routes

routes/api.php
$r->addRoute('GET', '/api/test', 'test_get');
$r->addRoute('POST', '/api/test', 'test_post');
$r->addRoute('GET', '/api/items', 'items_get');
$r->addRoute('POST', '/api/items', 'items_post');
Function handlers are referenced by their name as a string (e.g., 'test_get').

Handlers with Route Parameters

Handlers receive route parameters as an array argument:
index.php
function getid($var) {
    if (is_array($var)) {
        $id = $var['id'];
        $id2 = $var['id2'];
    }
    echo "given id: ".$id;
    echo "given id: ".$id2;
}

function delete($var) {
    echo $var['id'];
}

function postdata($var) {
    echo $var['test'];
    $data = json_decode(file_get_contents('php://input'), true);
    echo json_encode($data);
}
Used with parameterized routes:
routes/api.php
$r->get('/api/test/{id:\d+}/test/{id2:\d+}', 'getid');
$r->delete('/api/test/delete/{id:\d+}', 'delete');
$r->post('/api/test/{test:\d+}', 'postdata');

When to Use Function Handlers

Simple Endpoints

Quick, straightforward endpoints with minimal logic

Small Projects

Projects with a limited number of routes

Prototyping

Rapid development and testing of ideas

Standalone Routes

Routes that don’t share logic with others

Class-Based Handlers

Class-based handlers organize related functionality into reusable classes.

Defining a Handler Class

v1/test.php
<?php

class testing {

    public function display($id) {
        echo "given id: ".$id;
    }

    public function hello() {
        echo "Hello this class function call worked";
    }

    public function displaydata($id, $data) {
        echo json_encode($data);
        echo $id;
    }
}

Using Class Handlers in Routes

Include the class file and create an instance:
routes/api.php
include __DIR__."/../v1/test.php";
$obj = new testing;

return function (RouteCollector $r) {
    $obj = new testing;
    
    $r->addGroup('/api/projects', function (FastRoute\RouteCollector $r) use($obj) {
        $r->get('/testing/test', function() use($obj) {
            $obj->hello();
        });
        $r->get("/", function() use($obj) {
            $obj->display(1);
        });
    });
    
    $r->addGroup('/api/tasks', function (FastRoute\RouteCollector $r) use($obj) {
        $r->get("/", function() use($obj) {
            $obj->display(2);
        });
    });

    $r->get('/api/class', function() use($obj) {
        $obj->hello();
    });
};
Use the use($obj) syntax to make the class instance available inside closures.

When to Use Class Handlers

Shared Logic

Multiple routes that need access to common methods

Complex Business Logic

Routes requiring substantial processing or validation

Testability

Code that needs to be unit tested

Large Projects

Applications with many routes and features

Inline Closure Handlers

Inline closures are anonymous functions defined directly in the route definition.

Basic Closure Handler

routes/web.php
$r->get('/', function() {
    require __DIR__ . '/../views/main.php';
});

$r->get('/about', function() {
    require __DIR__ . '/../views/about.php';
});

Closures with Parameters

$r->get('/user/{id:\d+}', function($vars) {
    $userId = $vars['id'];
    echo json_encode(["user_id" => $userId]);
});

Closures with External Dependencies

routes/api.php
$obj = new testing;

$r->get('/api/class', function() use($obj) {
    $obj->hello();
});

When to Use Inline Closures

View Rendering

Routes that simply load a view file

Single-Use Logic

Logic that won’t be reused elsewhere

Quick Prototypes

Fast development without creating separate files

Glue Code

Simple bridges between routes and handlers

How Handlers Are Called

The dispatcher calls handlers using call_user_func():
index.php
switch ($routeInfo[0]) {
    case FastRoute\Dispatcher::FOUND:
        // Route found, call the handler
        $handler = $routeInfo[1];
        $var = $routeInfo[2];
        call_user_func($handler, $var);
        break;
}
The $var parameter contains an associative array of route parameters (e.g., ['id' => '123']).

Best Practices

  • Use function handlers for simple, standalone endpoints
  • Use class handlers for complex logic and code reuse
  • Use closures for view rendering and simple glue code
// For POST/PUT/PATCH requests
$data = json_decode(file_get_contents('php://input'), true);

// For GET requests
$param = $_GET['param'] ?? 'default';
// API responses should be consistent JSON
echo json_encode([
    "status" => "success",
    "data" => $result
]);
Always validate and sanitize route parameters and request data before using them.

Complete Handler Examples

Here’s a complete set of handler examples from the source code:
index.php
function helloworld() {
    echo json_encode(["hello"=>"HELLO WORLD! API IS WORKING LESGO!"]);
}

function test_get() {
    echo json_encode(["message" => "This is the test route (GET)"]);
}

function test_post() {
    $data = json_decode(file_get_contents('php://input'), true);
    echo json_encode(["message" => "POST request received", "data" => json_encode($data)]);
}

function items_get() {
    echo json_encode(["items" => ["item1", "item2", "item3"]]);
}

function items_post() {
    $data = json_decode(file_get_contents('php://input'), true);
    echo json_encode(["message" => "Item created", "item" => $data]);
}

function item_get_1() {
    echo json_encode(["item" => ["id" => 1, "name" => "Item 1"]]);
}

function getid($var) {
    if (is_array($var)) {
        $id = $var['id'];
        $id2 = $var['id2'];
    }
    echo "given id: ".$id;
    echo "given id: ".$id2;
}

function delete($var) {
    echo $var['id'];
}

function postdata($var) {
    echo $var['test'];
    $data = json_decode(file_get_contents('php://input'), true);
    echo json_encode($data);
}

Next Steps

Organizing Routes

Learn how to organize routes into separate files

API Routes

Create API endpoints with handlers

Build docs developers (and LLMs) love