aceitdesign / aceitrouter
A simple router that allows for nested pages as well as middleware before and after th main matching process. It functions on callbacks provided by the routes themselves. It also has support for default behaviour (404 etc)
Installs: 5
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/aceitdesign/aceitrouter
Requires
- php: >=7.0
This package is auto-updated.
Last update: 2025-12-24 15:24:30 UTC
README
AceitRouter
A Lightweight PHP Router.
Features
- Case-sensitive/case-insensitive URL matching
- Nested route definitions
- Prefix/suffix middleware
- Route-specific middleware
- Dynamic route parameters (e.g.
/users/{id})
Installation
composer require aceitdesign/router
Basic Usage
1. Initialize the Router
<?php require 'vendor/autoload.php';
$router = new AceitDesign\Router\AceitRouter( isCaseSensitive: false // Optional (default: false) );
When you create an instance of the router you can choose whether it will convert the entire URI to lowercase before any of the middleware or matching are called. To activate it, you can pass 'true' to the constructor
Defining Routes
1. Basic Route Structure
/**
* Routes are defined as arrays of path segments.
* Example: '/about/team' becomes ['about', 'team']
*/
$router->addRoute(['about', 'team'], function() {
echo "Our Team Page";
});
2. Route Handlers
/**
* The handler is stored under the last path segment.
* For ['about', 'team'], the structure becomes:
* [
* 'about' => [
* 'team' => [
* 'handler' => yourCallable
* ]
* ]
* ]
*/
$router->get(['products'], 'ProductController@index');
3. Route Parameters
/**
* Parameters are enclosed in {} and stored in the 'params' key.
* Only one parameter per segment is supported.
* Example: ['users', '{id}'] stores 'id' in the 'users' segment.
*/
$router->get(['users', '{id}'], function($params) {
echo "User ID: " . htmlspecialchars($params['id']);
});
/**
- Important: The router collects all parameters until the last handler.
- For ['users','{id}','posts','{post_id}'], all params are passed
to the final handler. */
4. HTTP Method Handling
/** * Methods are stored with each route definition. * Defaults to ['GET'] if not specified. */ $router->addRoute(['contact'], 'FormController@submit', ['POST']);
// Shortcut methods automatically set the HTTP method: $router->post(['login'], 'AuthController@login'); // Sets ['POST'] $router->put(['profile'], 'UserController@update'); // Sets ['PUT']
5. Middleware Integration
/**
* Middleware is stored with its route and executed before the handler.
* Global middleware should use addPrefixes() instead.
*/
$router->get(['admin'], 'AdminController@index', [
function() {
if (!is_admin()) {
header('Location: /login');
exit;
}
}
]);
Complete Example
/**
* RESTful user resource with parameters and middleware
*/
$router->get(['users'], 'UserController@index'); // GET /users
$router->post(['users'], 'UserController@store', [AuthMiddleware::class]); // POST /users
$router->get(['users', '{id}'], function($params) {
// $params contains ['id' => value]
}); // GET /users/42
$router->put(['users', '{id}'], 'UserController@update'); // PUT /users/42
$router->delete(['users', '{id}'], 'UserController@delete'); // DELETE /users/42
You can also skip the addRoute method, and use the setRoutes() method instead. This will accept a named array (nested or not) with all the routes in one go. If you are confident you have made no errors you can do something like:
[
'about' => [
'team' => [
'handler' => yourCallable,
'middleware'=>[callable array]
],
'company'=>['handler'=>callable]
]
]
Implementation Notes
- Path Segments: Always use arrays, e.g.,
['path', 'to', 'route'] - Parameters: Must be enclosed in
{}(one per segment) - Handlers: Receive parameters as an associative array
- Shortcuts:
get(),post(), etc. are preferred overaddRoute()
Example Workflow
// Define route with parameters
$router->addRoute(['users', '{id}', 'posts', '{post_id}'], function($params) {
// $params contains both id and post_id
echo "User: {$params['id']}, Post: {$params['post_id']}";
});
// Matches:
// /users/42/posts/99 → User: 42, Post: 99
3. Configure Fallbacks (Optional)
// 404 Handler
$router->setFallback(function() {
http_response_code(404);
echo "Page not found";
});
You can also set default callbacks for cases where a page is not found or any errors occur.
// Empty route handler
$router->setDefault(function() {
echo "Home Page";
});
4. Add Middleware
// Global middleware (runs on all routes)
$router->addPrefixes([
function() { /* CORS headers */ }
]);
$router->addSuffixes([
function() { /* CORS headers */ }
]);
5. Handle Requests
// In your entry point (e.g. index.php)
$router->handleRequest();
Advanced Examples
Nested Routes
$router->addRoute(['api', 'v1', 'users'], 'ApiController@users');
// Matches: /api/v1/users
Multiple Parameters
$router->addRoute(['posts', '{id}', 'comments', '{comment_id}'],
function($params) {
// $params contains both id and comment_id
}
);
// Matches: /posts/42/comments/99
Error Handling
The router provides three levels of fallback:
setDefault()- For empty paths (/)- Route-specific handlers - For valid routes
setFallback()- For 404 errors