Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

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

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.

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.
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
BackendPerformanceroutingPHPFastRoute

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion