Route2/README.md
2025-04-16 18:26:02 +02:00

5.2 KiB

Route2 🛣️

A simple routing system for PHP web applications.

Features:

  • Parameters: Flexible URL handling with parameters (e.g, /user/$id)
  • Middleware: Register callback functions to execute before and after route callback functions.
  • Groups: Organize routes under an optional prefix (e.g, /admin) and apply group-specific middleware.
  • Lightweight: A single-file, no-frills routing solution with zero dependencies.

Example:

// Initialize the router. This method must be called before defining any routes
Route2::setup(); 

// Define a GET route
Route2::get('/home', function () {
    echo "Welcome to the homepage!";
});

// Define a route with a parameter
Route2::get('/user/$id', function ($id) {
   echo "User ID: $id";
});

// Define a route with an optional parameter
Route2::get('/user/$id?', function ($id = null) {
   echo $id ? "User ID: $id" : "No User ID provided.";
});

// Defining middlewares
Route2::before(function () {
    echo "Middleware executed before the route callback.";
});
Route2::after(function () {
    echo "Middleware executed after the route callback.";
});

// Define a route with a middleware attached to it
Route2::post('/submit', function () {
    echo "Form submitted!";
}, function () {
    echo "Middleware executed before the callback.";
});

// Group routes under a common prefix
Route2::group('/admin', function () {
    // Middlewares defined here will not affect the routes outside this group
    Route2::before(function () {
        echo "Admin Middleware executed.";
    });
    Route2::get('/dashboard', function () {
        echo "Admin Dashboard";
    });
    Route2::post('/settings', function () {
        echo "Admin Settings";
    });
});

Installing

Composer:

Composer needs to know where to locate the package. Add the repository to your project by declaring it in the composer.json file.

{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/WilliamAAK/Route2"
        }
    ],
    "require": {
        "williamaak/route2": "dev-master"
    }
}

Fetch the package by running

composer install

Manual:

Its all in a single file; include it in your project like so.

require '/YourPath/Route2.php'

Using Route2

To get started quickly you may copy this into your project.

Classic mode

<?php

require __DIR__.'/vendor/autoload.php';

use WilliamAAK\Http\Route2;

Route2::setup();

Route2::get('/$world?', function($world = 'World') {
    echo "Hello, $world!";
});

// Since no route was found show a 404 page
http_response_code(404);
?>
<h1>Page not found!</h1>

FrankenPHP worker mode

Boot your application once and keep it in memory by using worker mode. Simply do what you would normally do but inside the handler.

<?php
// public/index.php

// Prevent worker script termination when a client connection is interrupted
ignore_user_abort(true);

// Boot your app
require __DIR__.'/vendor/autoload.php';

use WilliamAAK\Http\Route2;

// Handler outside the loop for better performance (doing less work)
$handler = static function () {
    // Called when a request is received,
    // superglobals, php://input and the like are reset
    Route2::setup(
        $_SERVER['REQUEST_URI']
    );

    Route2::get('/$world?', function($world = 'World') {
        echo "Hello, $world!";
    });

    // Since no route was found show a 404 page
    http_response_code(404);
    ?>
    <h1>Page not found!</h1>
    <?php
};

$maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0);
for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) {
    $keepRunning = \frankenphp_handle_request($handler);

    // Call the garbage collector to reduce the chances of it being triggered in the middle of a page generation
    gc_collect_cycles();

    if (!$keepRunning) break;
}

Accessing your routes

The simplest way to access your routes is to put the file in your folder and run it.

For example if you request http://your.site/yourscript.php/your/route it will automatically adjust to /your/route.

Rewriting requests

Want to hide that pesky script name (e.g index.php) from the URL?

FrankenPHP:

It is recommended that you use FrankenPHP; modern PHP app server. This behavior is enabled by default.

NGINX:

With PHP already installed and configured you may add this to the server block of your configuration to make requests that don't match a file on your server to be redirected to index.php

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Apache:

Make sure that mod_rewrite is installed on Apache. On a unix system you can just do a2enmod rewrite

This snippet in your .htaccess will ensure that all requests for files and folders that does not exists will be redirected to index.php

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]