Rebrand2 Route2

This commit is contained in:
William 2025-04-16 15:35:57 +02:00
parent c413451500
commit 1857375b8b
3 changed files with 197 additions and 100 deletions

105
README.md
View File

@ -1,6 +1,6 @@
# Route
# Route2
A lightweight routing system for handling HTTP requests.
A simple routing system for PHP web applications.
### Features:
- Define routes for specific HTTP methods (GET, POST, PUT, DELETE, etc.).
@ -10,46 +10,49 @@ A lightweight routing system for handling HTTP requests.
### Example:
```php
// Setup the routing context. This method must be called before defining any routes
Route2::setup();
// Define a GET route
Route::get('/home', function () {
Route2::get('/home', function () {
echo "Welcome to the homepage!";
});
// Define a route with a parameter
Route::get('/user/$id', function ($id) {
Route2::get('/user/$id', function ($id) {
echo "User ID: $id";
});
// Define a route with an optional parameter
Route::get('/user/$id?', function ($id = null) {
Route2::get('/user/$id?', function ($id = null) {
echo $id ? "User ID: $id" : "No User ID provided.";
});
// Defining middlewares
Route::before(function () {
Route2::before(function () {
echo "Middleware executed before the route callback.";
});
Route::after(function () {
Route2::after(function () {
echo "Middleware executed after the route callback.";
});
// Define a route with a middleware attached to it
Route::post('/submit', function () {
Route2::post('/submit', function () {
echo "Form submitted!";
}, function () {
echo "Middleware executed before the callback.";
});
// Group routes under a common prefix
Route::group('/admin', function () {
Route2::group('/admin', function () {
// Middlewares defined here will not affect the routes outside this group
Route::before(function () {
Route2::before(function () {
echo "Admin Middleware executed.";
});
Route::get('/dashboard', function () {
Route2::get('/dashboard', function () {
echo "Admin Dashboard";
});
Route::post('/settings', function () {
Route2::post('/settings', function () {
echo "Admin Settings";
});
});
@ -65,7 +68,7 @@ Composer needs to know where to locate the package. Add the repository to your p
"repositories": [
{
"type": "vcs",
"url": "https://github.com/WilliamAAK/Route"
"url": "https://github.com/WilliamAAK/Route2"
}
],
"require": {
@ -82,29 +85,87 @@ Fetch the package by running
Its all in a single file; include it in your project like so.
```php
require '/YourPath/Route.php'
require '/YourPath/Route2.php'
```
# Usage
To get started quickly you may copy this into your project.
```php
use WilliamAAK\Http\Route;
### Classic mode
Route::get('/$world?', function($world = 'World') {
Defualt PHP behavior
```php
<?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 matched show a 404 page
// Since no route was found show a 404 page
http_response_code(404);
?>
<h1>Page not found!</h1>
```
The simplest way to access your routes is to put the file in your favorite 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`
### FrankenPHP worker mode
# Rewrite requests
Boot your application once and keep it in memory by using [worker mode](https://frankenphp.dev/docs/worker/). Simply do what you would normally do but inside the handler.
```php
<?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?
@ -124,9 +185,7 @@ location / {
### Apache:
Make sure that mod_rewrite is installed on Apache. On a unix system you can just do
`a2enmod rewrite`
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`

186
Route.php
View File

@ -5,7 +5,7 @@ namespace WilliamAAK\Http;
use InvalidArgumentException;
/**
* A lightweight routing system for handling HTTP requests.
* A simple routing system for PHP web applications.
*
* ### Features:
* - Define routes for specific HTTP methods (GET, POST, PUT, DELETE, etc.).
@ -15,46 +15,49 @@ use InvalidArgumentException;
*
* ### Example:
* ```php
* // Setup the routing context. This method must be called before defining any routes
* Route2::setup();
*
* // Define a GET route
* Route::get('/home', function () {
* Route2::get('/home', function () {
* echo "Welcome to the homepage!";
* });
*
* // Define a route with a parameter
* Route::get('/user/$id', function ($id) {
* Route2::get('/user/$id', function ($id) {
* echo "User ID: $id";
* });
*
* // Define a route with an optional parameter
* Route::get('/user/$id?', function ($id = null) {
* Route2::get('/user/$id?', function ($id = null) {
* echo $id ? "User ID: $id" : "No User ID provided.";
* });
*
* // Defining middlewares
* Route::before(function () {
* Route2::before(function () {
* echo "Middleware executed before the route callback.";
* });
* Route::after(function () {
* Route2::after(function () {
* echo "Middleware executed after the route callback.";
* });
*
* // Define a route with a middleware attached to it
* Route::post('/submit', function () {
* Route2::post('/submit', function () {
* echo "Form submitted!";
* }, function () {
* echo "Middleware executed before the callback.";
* });
*
* // Group routes under a common prefix
* Route::group('/admin', function () {
* Route2::group('/admin', function () {
* // Middlewares defined here will not affect the routes outside this group
* Route::before(function () {
* Route2::before(function () {
* echo "Admin Middleware executed.";
* });
* Route::get('/dashboard', function () {
* Route2::get('/dashboard', function () {
* echo "Admin Dashboard";
* });
* Route::post('/settings', function () {
* Route2::post('/settings', function () {
* echo "Admin Settings";
* });
* });
@ -64,11 +67,35 @@ use InvalidArgumentException;
* @version 1.0.0
* @author WilliamAAK
*/
class Route
class Route2
{
static string $pathPrefix = '';
static array $before = [ [ ] ];
static array $after = [ [ ] ];
/**
* Router state variables.
*/
private static string $routePrefix;
private static array $beforeMiddleware;
private static array $afterMiddleware;
private static string $requestUri;
private static string $requestMethod;
/**
* Setup the routing context. This method must be called before defining any routes.
*
* If no request URI or method is provided, it will use the current request's URI and method.
*
* @param string|null $requestUri The request URI (optional).
* @param string|null $requestMethod The request method (optional).
*
* @return void
*/
static function setup(?string $requestUri = null, ?string $requestMethod = null)
{
self::$routePrefix = '';
self::$beforeMiddleware = [[]];
self::$afterMiddleware = [[]];
self::$requestUri = urldecode($requestUri ?? self::getRelativeRequestPath());
self::$requestMethod = strtoupper($requestMethod ?? $_SERVER['REQUEST_METHOD']);
}
/**
* Retrieves the relative path of the current HTTP request.
@ -86,13 +113,7 @@ class Route
*/
static function getRelativeRequestPath(): string
{
static $requestUrlPath;
if (isset($requestUrlPath)) {
return $requestUrlPath;
}
$requestUrlPath = urldecode(strtok($_SERVER['REQUEST_URI'], '?'));
$requestUrlPath = strtok($_SERVER['REQUEST_URI'], '?');
$scriptName = $_SERVER['SCRIPT_NAME'];
$scriptDir = dirname($scriptName) . '/';
@ -113,12 +134,13 @@ class Route
}
/**
* Matches an incoming HTTP request to a defined route and executes the callback.
* Matches the current HTTP request to a defined route. If the route matches it runs the corresponding
* callback and middlewares before terminating the script.
*
* ### Examples:
* 1. Matching a route with parameters:
* ```php
* Route::match('GET', '/user/$id', function ($id) {
* Route2::match('GET', '/user/$id', function ($id) {
* echo "User ID: $id";
* });
* ```
@ -127,7 +149,7 @@ class Route
*
* 2. Matching a route with optional parameters:
* ```php
* Route::match('GET', '/user/$id?', function ($id = null) {
* Route2::match('GET', '/user/$id?', function ($id = null) {
* echo $id ? "User ID: $id" : "No User ID";
* });
* ```
@ -144,21 +166,21 @@ class Route
static function match(string $methods, string $route, callable $callback, ?callable $middleware = null): void
{
$allowedMethods = array_map(strtoupper(...), explode('|', $methods));
if (!in_array($_SERVER['REQUEST_METHOD'], $allowedMethods)) {
if (!in_array(self::$requestMethod, $allowedMethods, true)) {
return;
}
$requestPathParts = explode('/', self::getRelativeRequestPath());
$routeParts = explode('/', self::$pathPrefix . $route);
$callbackArgs = [];
$requestParts = explode('/', self::$requestUri);
$routeParts = explode('/', self::$routePrefix . $route);
$callbackArgs = [];
if (count($requestPathParts) !== count($routeParts)) {
if (count($requestParts) !== count($routeParts)) {
return;
}
for ($i = 1; $i < count($routeParts); $i++) {
$routePart = $routeParts[$i] ?? '';
$requestPart = $requestPathParts[$i] ?? '';
$requestPart = $requestParts[$i] ?? '';
if ($routePart === '') {
continue;
@ -182,13 +204,13 @@ class Route
}
if ($requestPart !== '') {
$callbackArgs[] = htmlspecialchars($requestPart);
$callbackArgs[] = $requestPart;
}
$requestPathParts[$i] = $routePart;
$requestParts[$i] = $routePart;
}
if (implode('/', $routeParts) !== implode('/', $requestPathParts)) {
if (implode('/', $routeParts) !== implode('/', $requestParts)) {
return;
}
@ -196,7 +218,7 @@ class Route
self::before($middleware);
}
foreach (self::$before as $middlewares) {
foreach (self::$beforeMiddleware as $middlewares) {
foreach ($middlewares as $middleware) {
$middleware();
}
@ -204,7 +226,7 @@ class Route
$callback(...$callbackArgs);
foreach (self::$after as $middlewares) {
foreach (self::$afterMiddleware as $middlewares) {
foreach ($middlewares as $middleware) {
$middleware();
}
@ -214,59 +236,75 @@ class Route
}
/**
* Shorthand for Route::match('GET', ...).
* Shorthand for Route2::match('GET', ...).
*/
static function get(string $route, callable $callback, ?callable $middleware = null): void
{self::match('get', $route, $callback, $middleware);}
{
self::match('get', $route, $callback, $middleware);
}
/**
* Shorthand for Route::match('POST', ...).
* Shorthand for Route2::match('POST', ...).
*/
static function post(string $route, callable $callback, ?callable $middleware = null): void
{self::match('post', $route, $callback, $middleware);}
{
self::match('post', $route, $callback, $middleware);
}
/**
* Shorthand for Route::match('PUT', ...).
* Shorthand for Route2::match('PUT', ...).
*/
static function put(string $route, callable $callback, ?callable $middleware = null): void
{self::match('put', $route, $callback, $middleware);}
{
self::match('put', $route, $callback, $middleware);
}
/**
* Shorthand for Route::match('PATCH', ...).
* Shorthand for Route2::match('PATCH', ...).
*/
static function patch(string $route, callable $callback, ?callable $middleware = null): void
{self::match('patch', $route, $callback, $middleware);}
{
self::match('patch', $route, $callback, $middleware);
}
/**
* Shorthand for Route::match('DELETE', ...).
* Shorthand for Route2::match('DELETE', ...).
*/
static function delete(string $route, callable $callback, ?callable $middleware = null): void
{self::match('delete', $route, $callback, $middleware);}
{
self::match('delete', $route, $callback, $middleware);
}
/**
* Shorthand for Route::match('OPTIONS', ...).
* Shorthand for Route2::match('OPTIONS', ...).
*/
static function options(string $route, callable $callback, ?callable $middleware = null): void
{self::match('options', $route, $callback, $middleware);}
{
self::match('options', $route, $callback, $middleware);
}
/**
* Shorthand for Route::match('GET|POST', ...).
* Shorthand for Route2::match('GET|POST', ...).
*/
static function form(string $route, callable $callback, ?callable $middleware = null): void
{self::match('get|post', $route, $callback, $middleware);}
{
self::match('get|post', $route, $callback, $middleware);
}
/**
* Shorthand for Route::match('GET|POST|PUT|PATCH|DELETE|OPTIONS', ...).
* Shorthand for Route2::match('GET|POST|PUT|PATCH|DELETE|OPTIONS', ...).
*/
static function any(string $route, callable $callback, ?callable $middleware = null): void
{self::match('get|post|put|patch|delete|options', $route, $callback, $middleware);}
{
self::match('get|post|put|patch|delete|options', $route, $callback, $middleware);
}
/**
* Registers middleware to be executed before the route callback.
*
* ### Example:
* ```php
* Route::before(function () {
* Route2::before(function () {
* echo "Middleware executed before the route callback.";
* });
* ```
@ -278,7 +316,7 @@ class Route
static function before(callable $middleware): void
{
array_push(
self::$before[array_key_last(self::$before)],
self::$beforeMiddleware[array_key_last(self::$beforeMiddleware)],
$middleware
);
}
@ -288,7 +326,7 @@ class Route
*
* ### Example:
* ```php
* Route::after(function () {
* Route2::after(function () {
* echo "Middleware executed after the route callback.";
* });
* ```
@ -300,7 +338,7 @@ class Route
static function after(callable $middleware): void
{
array_push(
self::$after[array_key_last(self::$after)],
self::$afterMiddleware[array_key_last(self::$afterMiddleware)],
$middleware
);
}
@ -312,8 +350,8 @@ class Route
* ### Examples:
* 1. Grouping routes under a prefix:
* ```php
* Route::group('/admin', function () {
* Route::get('/dashboard', function () {
* Route2::group('/admin', function () {
* Route2::get('/dashboard', function () {
* echo "Admin Dashboard";
* });
* });
@ -323,43 +361,43 @@ class Route
*
* 2. Grouping middlewares and routes but this time without a prefix:
* ```php
* Route::group(callback: function () {
* Route::before(function () {
* Route2::group(callback: function () {
* Route2::before(function () {
* echo "Hello routes from within or nested groups! ";
* });
* // Outputs: "Hello routes from within or nested groups! Hello from somewhere!"
* Route::get('/somewhere', function () {
* Route2::get('/somewhere', function () {
* echo "Hello from somewhere!";
* });
* });
*
* // Outputs: "I am unaffected by that group middleware."
* Route::get('/', function () {
* Route2::get('/', function () {
* echo "I am unaffected by that group middleware.";
* });
* ```
* @param string|null $prefix The optional path prefix for the group (e.g., "/admin").
* @param callable|null $callback The callback containing the route definitions for the group.
*
* @param string|null $routePrefix The optional route prefix for the group (e.g., "/admin").
* @param callable|null $callback The callback containing the route definitions for the group.
* @throws InvalidArgumentException If the callback is not provided.
*
* @return void
*/
static function group(?string $prefix = null, ?callable $callback = null): void
static function group(?string $routePrefix = null, ?callable $callback = null): void
{
if ($callback === null) {
throw new InvalidArgumentException('You must provide a callback.');
}
if (!str_starts_with(
self::getRelativeRequestPath(),
self::$pathPrefix . $prefix ?? ''
self::$requestUri,
self::$routePrefix . $routePrefix ?? ''
)) return;
self::$pathPrefix = self::$pathPrefix . $prefix ?? '';
array_push(self::$before, []);
array_push(self::$after, []);
self::$routePrefix = self::$routePrefix . $routePrefix ?? '';
array_push(self::$beforeMiddleware, []);
array_push(self::$afterMiddleware, []);
$callback();
array_pop(self::$before);
array_pop(self::$after);
self::$pathPrefix = rtrim(self::$pathPrefix, $prefix ?? '');
array_pop(self::$beforeMiddleware);
array_pop(self::$afterMiddleware);
self::$routePrefix = rtrim(self::$routePrefix, $routePrefix ?? '');
}
}

View File

@ -1,6 +1,6 @@
{
"name": "williamaak/route",
"description": " A lightweight routing system for handling HTTP requests.",
"name": "williamaak/route2",
"description": "A simple routing system for PHP web applications.",
"type": "library",
"require": {
"php": ">=8.1.0"