5.1 KiB
Route2
A simple routing system for PHP web applications.
Features:
- Define routes for specific HTTP methods (GET, POST, PUT, DELETE, etc.).
- Apply middleware to routes or groups of routes.
- Group routes under a common prefix for better organization.
- Support for route parameters (e.g.,
/user/$id
) and optional parameters (e.g.,/user/$id?
).
Example:
// Setup the routing context. 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";
});
});
Installation
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'
Usage
To get started quickly you may copy this into your project.
Classic mode
Defualt PHP behavior
<?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. E.g if you request http://your.site/yourscript.php/your/route
the route will be automatically converted 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 the 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]