定制 scriptmancer/piri 二次开发

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

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

scriptmancer/piri

Composer 安装命令:

composer require scriptmancer/piri

包简介

A modern, attribute-based PHP router with powerful features for building web applications

README 文档

README

A lightweight, attribute-based PHP router with support for middleware, route groups, and parameter validation.

Features

  • Attribute-based routing for clean controller definitions
  • Support for route parameters with regex pattern validation
  • Middleware support (global, group, and route-specific)
  • Route groups for organizing related routes
  • Named routes for easy URL generation
  • Namespace-based controller registration
  • Type conversion for route parameters
  • PSR-7 compatible

Installation

composer require yourusername/piri-router

Basic Usage

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

use Piri\Core\Router;
use Piri\Attributes\Route;

// Create a new router instance
$router = new Router();

// Register a controller
$router->registerClass(HomeController::class);

// Define a route using a closure
$router->get('/', function() {
    return 'Hello, World!';
});

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

Controller Example

use Piri\Attributes\Route;

class HomeController
{
    #[Route('/')]
    public function index(): string
    {
        return 'Welcome to the homepage!';
    }
    
    #[Route('/about')]
    public function about(): string
    {
        return 'About us page';
    }
}

Route Patterns

You can use regex patterns in your route parameters:

// Numeric ID parameter
#[Route('/users/{id:\d+}')]
public function numericId(array $params): string
{
    // The id parameter will only match digits
    $id = $params['id']; // Will be a string of digits
    return 'User ID: ' . $id;
}

// Alphabetic username parameter
#[Route('/users/{username:[a-zA-Z]+}')]
public function alphaUsername(array $params): string
{
    // The username parameter will only match letters
    $username = $params['username']; // Will be a string of letters
    return 'Username: ' . $username;
}

// Using method calls
$router->get('/posts/{id:\d+}', function(array $params) {
    $id = $params['id'];
    return 'Post ID: ' . $id;
});

Handling Route Parameters

All route parameters are passed to your handler method as a single array. You should always define your handler method to accept an array parameter, and then access the route parameters from that array:

#[Route('/users/{id}/posts/{postId?}')]
public function posts(array $params): array
{
    // Access parameters from the $params array
    $id = $params['id'];
    $postId = $params['postId'] ?? null; // Use null coalescing for optional parameters
    
    return [
        'user' => $id,
        'post' => $postId
    ];
}

Route Groups

You can group routes together using the RouteGroup attribute on controller classes:

#[RouteGroup(prefix: '/api', name: 'api', middleware: [ApiAuthMiddleware::class])]
class ApiController
{
    #[Route('/users', name: 'users.list')]
    public function listUsers(): array
    {
        // This route will be accessible at /api/users
        // It will have the middleware ApiAuthMiddleware applied
        // Its name will be api.users.list
        return ['users' => []];
    }
    
    #[Route('/users/{id:\d+}')]
    public function getUser(array $params): array
    {
        // This route will be accessible at /api/users/{id}
        // It will also have the middleware ApiAuthMiddleware applied
        return ['user' => ['id' => $params['id']]];
    }
}

Namespace Registration

You can register all controllers in a namespace at once:

// Register all controllers in the App\Controller namespace
$router->registerNamespace('App\Controller');

// Register with prefix, name, and middleware
$router->registerNamespace(
    'App\Api\Controller', 
    prefix: '/api', 
    name: 'api', 
    middleware: [ApiAuthMiddleware::class]
);

This will automatically register all controllers in the specified namespace and apply the prefix, name, and middleware to all routes in those controllers.

Middleware

Middleware allows you to filter HTTP requests entering your application:

// Define a middleware class
class AuthMiddleware implements MiddlewareInterface
{
    public function handle(callable $next, array $parameters = []): mixed
    {
        // Check if user is authenticated
        if (!isset($_SESSION['user'])) {
            http_response_code(401);
            return 'Unauthorized';
        }
        
        // Call the next middleware or the route handler
        return $next($parameters);
    }
}

// Apply middleware globally
$router->addGlobalMiddleware(new LoggingMiddleware());

// Apply middleware to a group
$router->group(['prefix' => '/admin', 'middleware' => [new AuthMiddleware()]], function($router) {
    $router->get('/dashboard', [AdminController::class, 'dashboard']);
});

// Apply middleware to a specific route
$router->get('/profile', [UserController::class, 'profile'], 
    middleware: [new AuthMiddleware()]);
    
// Apply middleware using attributes
#[Route('/settings', middleware: [AuthMiddleware::class])]
public function settings(): string
{
    return 'Settings page';
}

Error Handling

You can customize error handling by providing an error handler function to the handle method:

// Custom error handling
$router->handle([
    'error_handler' => function(\Exception $e) {
        if ($e instanceof RouteNotFoundException) {
            http_response_code(404);
            include 'templates/404.php';
        } else {
            http_response_code(500);
            error_log($e->getMessage());
            include 'templates/500.php';
        }
    }
]);

Advanced Usage

For more advanced usage, including route caching, custom request handling, and more, please refer to the Documentation.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgements

  • Inspired by modern PHP routing libraries
  • Built with PHP 8.1+ features in mind

scriptmancer/piri 适用场景与选型建议

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

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

围绕 scriptmancer/piri 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-03-07