aceitdesign/aceitrouter 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

aceitdesign/aceitrouter

Composer 安装命令:

composer require 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)

关键字:

README 文档

README

AceitRouter

A Lightweight PHP Router.

PHP Version License

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 over addRoute()

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:

  1. setDefault() - For empty paths (/)
  2. Route-specific handlers - For valid routes
  3. setFallback() - For 404 errors

统计信息

  • 总下载量: 5
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-05-14