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.
anunes/anrouter 适用场景与选型建议
anunes/anrouter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 10 月 27 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「framework」 「routing」 「php」 「router」 「middleware」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 anunes/anrouter 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 anunes/anrouter 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 anunes/anrouter 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
PHP Framework HLEB2 is the foundation of the web application. Provides ease of development and application performance.
Write down your routing mapping at one place
Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.
Client for Google Directions API to add interpolated points to a route consisting of given coordinates.
Alfabank REST API integration
A router designed for web requests for the Monolith framework
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 10
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-27