Boost PHP Routing Performance with FastRoute: A Step‑by‑Step Guide

This tutorial walks you through creating a PHP project, initializing Composer, installing the FastRoute library, configuring routes with example code, running the built‑in server, and analyzing how call_user_func and routeInfo work to achieve high‑performance routing.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Boost PHP Routing Performance with FastRoute: A Step‑by‑Step Guide

Overview

FastRoute is a lightweight PHP routing library that focuses on performance by compiling all route information once, avoiding costly string‑matching on each request, and using regular‑expression‑based routing.

Create a New Project

mkdir HelloFastRoute
cd HelloFastRoute

Initialize Composer

Run composer init in the project directory to generate a composer.json file. Define the package name, author, and PSR‑4 autoload mapping for the Tinywan\HelloFastRoute\ namespace pointing to src/.

Install FastRoute

composer require nikic/fast-route

Configure Routes

Create an index.php file and add the following code:

<?php
declare(strict_types=1);
require 'vendor/autoload.php';

$dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/user/{userId}/info', function ($args) {
        echo '[x][开源技术小栈] User ID: ' . $args['userId'];
    });
});

$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
if (false !== $pos = strpos($uri, '?')) {
    $uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);

$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
    case FastRoute\Dispatcher::NOT_FOUND:
        http_response_code(404);
        echo "404 Not Found";
        break;
    case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        http_response_code(405);
        echo "405 Method Not Allowed";
        break;
    case FastRoute\Dispatcher::FOUND:
        $handler = $routeInfo[1];
        $vars = $routeInfo[2];
        call_user_func($handler, $vars);
        break;
}

Start PHP's built‑in server from the project directory: php -S localhost:8888 Visiting http://localhost:8888/user/2024/info will output:

[x][开源技术小栈] User ID: 2024

Code Analysis

The call_user_func function invokes a callback with supplied arguments. In the routing example it executes the anonymous function defined in addRoute when the URL matches the pattern. $routeInfo[0] holds the dispatch result (e.g., FastRoute\Dispatcher::FOUND). $routeInfo[1] contains the handler – the anonymous function associated with the matched route. $routeInfo[2] is an associative array of route parameters extracted from the URL (e.g., ['userId' => '2024']).

When a request matches /user/{userId}/info, the dispatcher returns FOUND, the handler is retrieved, and call_user_func($handler, $vars) runs the function, printing the user ID.

Specifically, the anonymous function is defined in the addRoute call and stored as $handler . The extracted $vars are passed to it, enabling dynamic handling based on URL parameters.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendperformanceroutingPHPFastRoute
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.