anunes/anrouter
Composer 安装命令:
composer require anunes/anrouter
包简介
A lightweight PHP router with middleware support, route groups, and named routes
README 文档
README
A lightweight PHP router with middleware support, route groups, and named routes.
Features
- 🚀 Simple and intuitive API
- 🛡️ Middleware support with aliases
- 📦 Route groups with prefixes
- 🏷️ Named routes for URL generation
- ⚡ Fast route matching with regex
- 🔧 PSR-4 autoloading compatible
- 🧪 PHP 8.0+ compatible
Installation
Install via Composer:
composer require anunes/anrouter
Quick Start
<?php require 'vendor/autoload.php'; use AnRouter\Router; $router = new Router(); // Basic routes $router->get('/', function() { return 'Hello World!'; }); $router->post('/users', [UserController::class, 'store']); // Route with parameters $router->get('/users/{id}', function($id) { return "User ID: $id"; }); // Named routes $router->get('/profile', function() { return 'User Profile'; })->name('profile'); // Dispatch the current request $method = $_SERVER['REQUEST_METHOD']; $uri = $_SERVER['REQUEST_URI']; echo $router->dispatch($method, $uri);
Route Definition
HTTP Methods
$router->get('/path', $handler); $router->post('/path', $handler); $router->put('/path', $handler); $router->delete('/path', $handler);
Route Handlers
Routes can accept different types of handlers:
// Closure $router->get('/', function() { return 'Hello!'; }); // Controller array [ControllerClass, 'method'] $router->get('/users', [UserController::class, 'index']); // Any callable $router->get('/callback', 'some_function');
Route Parameters
Use curly braces to define route parameters:
$router->get('/users/{id}', function($id) { return "User: $id"; }); $router->get('/posts/{slug}/comments/{id}', function($slug, $id) { return "Post: $slug, Comment: $id"; });
Named Routes
Assign names to routes for easy URL generation:
$router->get('/users/{id}', [UserController::class, 'show']) ->name('user.show'); // Generate URLs $url = $router->route('user.show', ['id' => 123]); // Returns: /users/123
Route Groups
Group routes with common attributes:
// Group with prefix $router->group(['prefix' => 'api/v1'], function($router) { $router->get('/users', [UserController::class, 'index']); $router->post('/users', [UserController::class, 'store']); }); // Group with middleware $router->group(['middleware' => ['auth']], function($router) { $router->get('/dashboard', [DashboardController::class, 'index']); $router->get('/profile', [ProfileController::class, 'show']); }); // Combined prefix and middleware $router->group([ 'prefix' => 'admin', 'middleware' => ['auth', 'admin'] ], function($router) { $router->get('/users', [AdminController::class, 'users']); });
Middleware
Basic Middleware
// Middleware function $router->get('/protected', function() { return 'Protected content'; })->middleware('auth'); // Multiple middleware $router->get('/admin', function() { return 'Admin panel'; })->middleware('auth', 'admin');
Middleware Classes
Create middleware classes with an __invoke method:
class AuthMiddleware { public function __invoke() { if (!isset($_SESSION['user'])) { http_response_code(401); echo 'Unauthorized'; return false; // Stop execution } return true; // Continue } } // Register middleware $router->get('/dashboard', function() { return 'Dashboard'; })->middleware(AuthMiddleware::class);
Middleware Aliases
Create a middleware configuration file to define aliases:
// config/middleware.php return [ 'auth' => AuthMiddleware::class, 'admin' => AdminMiddleware::class, 'cors' => CorsMiddleware::class, ];
Load middleware aliases:
$router->loadMiddlewareAliases('/path/to/config/middleware.php');
Advanced Usage
Custom Fallback Handler
Provide a custom handler for unmatched routes:
$fallback = function($method, $uri) { http_response_code(404); return "Custom 404: Route $method $uri not found"; }; echo $router->dispatch($method, $uri, $fallback);
Getting Route Information
// Get all registered routes $routes = $router->getRoutes(); // Get all named routes $namedRoutes = $router->getNamedRoutes();
Route Debugging
Enable error logging to debug route matching:
// The router logs detailed information when matching routes error_reporting(E_ALL); ini_set('display_errors', 1);
Example Application
Here's a complete example of a simple API:
<?php require 'vendor/autoload.php'; use AnRouter\Router; $router = new Router(); // Middleware class CorsMiddleware { public function __invoke() { header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type'); return true; } } // API routes with CORS middleware $router->group(['prefix' => 'api', 'middleware' => [CorsMiddleware::class]], function($router) { // Users endpoint $router->get('/users', function() { return json_encode(['users' => []]); }); $router->get('/users/{id}', function($id) { return json_encode(['user' => ['id' => $id]]); }); $router->post('/users', function() { return json_encode(['message' => 'User created']); }); }); // Handle the request $method = $_SERVER['REQUEST_METHOD']; $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); try { echo $router->dispatch($method, $uri); } catch (Exception $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); }
Requirements
- PHP 8.0 or higher
- Composer for autoloading
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Support
If you find this package useful, please consider starring the repository!
For issues and questions, please use the GitHub Issues page.
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-27