定制 blackbonjour/slim-route-registry 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

blackbonjour/slim-route-registry

Composer 安装命令:

composer require blackbonjour/slim-route-registry

包简介

Attribute based route registry for Slim 4.

README 文档

README

A PHP library that provides attribute-based route registration for Slim Framework applications. This library allows you to define routes using PHP 8 attributes on your handler classes and methods, making your code more declarative and organized.

Requirements

  • PHP 8.2 or higher
  • Slim Framework 4.14 or higher
  • composer/class-map-generator 1.6 or higher

Installation

You can install the library via Composer:

composer require blackbonjour/slim-route-registry

Basic Usage

1. Create a Route Handler

Create a class that will handle your route and add the Route attribute to it:

<?php

namespace App\Handlers;

use BlackBonjour\SlimRouteRegistry\Route;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

#[Route('GET', '/hello')]
class HelloHandler
{
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $response->getBody()->write('Hello, World!');

        return $response;
    }
}

2. Register Routes with the RouteRegistry

In your application bootstrap file:

<?php

use BlackBonjour\SlimRouteRegistry\RouteRegistry;
use Slim\Factory\AppFactory;

require_once __DIR__ . '/vendor/autoload.php';

// Create Slim App
$app = AppFactory::create();

// Create RouteRegistry with paths to scan for route handlers
// By default, it uses ComposerClassProvider to find classes in the specified paths
$routeRegistry = new RouteRegistry([__DIR__ . '/src/Handlers']);

// Register all routes from the specified paths
$routeRegistry->register($app);

// Run the app
$app->run();

Advanced Usage

Named Routes

You can assign names to your routes for easier URL generation:

#[Route('GET', '/user/{id}', 'user-profile')]
class UserProfileHandler
{
    // ...
}

Multiple HTTP Methods

You can specify multiple HTTP methods for a single route:

#[Route(['GET', 'POST'], '/form')]
class FormHandler
{
    // ...
}

Method-Level Routes

You can also define routes on public methods:

class UserHandler
{
    #[Route('GET', '/users')]
    public function listUsers(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        // List users
        return $response;
    }

    #[Route('GET', '/users/{id}')]
    public function getUser(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        // Get specific user
        return $response;
    }
}

Route Arguments

You can pass additional arguments to your routes:

#[Route('GET', '/api/users', 'users-list', arguments: ['version' => 'v1', 'cache' => true])]
class UsersListHandler
{
    // ...
}

These arguments can be used to configure the route or provide additional data to the handler.

Middleware

You can attach middleware to your routes:

#[Route('GET', '/secure', 'secure-area', middlewares: [AuthMiddleware::class])]
class SecureAreaHandler
{
    // ...
}

Redirects

You can define redirects using the Redirect attribute:

#[Redirect('/old-path', '/new-path')]
#[Route('GET', '/new-path')]
class NewPathHandler
{
    // ...
}

You can also specify the HTTP status code for the redirect (defaults to 302):

#[Redirect('/legacy', '/modern', 301)]

When used with a Route attribute, you can omit the destination path to redirect to the route's path:

#[Redirect('/old-path')]
#[Route('GET', '/new-path')]
class NewPathHandler
{
    // ...
}

API Reference

RouteRegistry

The main class responsible for registering routes.

public function __construct(array $paths, ClassProviderInterface $classProvider = new ComposerClassProvider())
  • $paths: Array of directory paths to scan for route handler classes
  • $classProvider: Instance of ClassProviderInterface (defaults to ComposerClassProvider)
public function register(App $app): void
  • $app: Slim Framework App instance

ClassProviderInterface

An interface for classes that provide a list of class names from a given path.

public function provideClasses(string $path): array
  • $path: Directory path to scan for classes
  • Returns: Array of fully qualified class names

ComposerClassProvider

The default implementation of ClassProviderInterface that uses Composer's ClassMapGenerator to find classes.

public function __construct(ClassMapGenerator $classMapGenerator = new ClassMapGenerator())
  • $classMapGenerator: Optional custom instance of Composer's ClassMapGenerator (defaults to a new instance)
public function provideClasses(string $path): array
  • $path: Directory path to scan for classes
  • Returns: Array of fully qualified class names found in the path
  • Throws: DirectoryNotFoundExceptionClass if the path is not a valid directory
  • Throws: ClassMapGeneratorExceptionClass if the ClassMapGenerator encounters an error

Route Attribute

#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
public function __construct(
    array|string $methods,
    string $path,
    ?string $name = null,
    array $arguments = [],
    array $middlewares = [],
    array $redirects = []
)
  • $methods: HTTP method(s) as string or array of strings (e.g., 'GET', ['GET', 'POST'])
  • $path: URL path pattern (e.g., '/users/{id}')
  • $name: Optional route name for URL generation
  • $arguments: Array of key-value pairs to be passed to the route
  • $middlewares: Array of middleware classes, callables, or string class names
  • $redirects: Array of Redirect objects

Redirect Attribute

#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
public function __construct(
    string $from,
    ?string $to = null,
    int $status = 302
)
  • $from: Source path to redirect from
  • $to: Destination path (can be null if used with a Route attribute)
  • $status: HTTP status code for the redirect (defaults to 302)

License

This library is licensed under the MIT License. See the LICENSE file for details.

blackbonjour/slim-route-registry 适用场景与选型建议

blackbonjour/slim-route-registry 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 04 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「routing」 「attribute」 「slim」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 blackbonjour/slim-route-registry 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 blackbonjour/slim-route-registry 我们能提供哪些服务?
定制开发 / 二次开发

基于 blackbonjour/slim-route-registry 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-04-06