gacela-project / router

一个极简的HTTP路由器。

0.12.1 2023-12-21 22:17 UTC

This package is auto-updated.

Last update: 2024-09-06 11:54:35 UTC


README

一个极简的HTTP路由器,非常适合你的原型项目和解耦控制器。

GitHub Build Status Scrutinizer Code Quality Scrutinizer Code Coverage Psalm Type-coverage Status Mutation testing badge MIT Software License

为什么?

市面上有很多其他的路由器,例如:使用Symfony框架、Laravel等,但是它们功能丰富,意味着会给你的供应商添加很多意外的复杂性和依赖,你可能想要避免。至少对于你的原型项目。

Gacela Router 并不旨在成为能做所有事情的最好路由器,而是一个轻量级的路由器,拥有最基本的功能,非常适合你的简单想法出现。

对于原型,我们重视简洁性而非功能丰富的库。

安装

composer require gacela-project/router

示例

# `Bindings` and `Handlers` are optional, and you can place them in any order.

$router = new Router(function (Routes $routes, Bindings $bindings, Handlers $handlers) {

    // Custom redirections
    $routes->redirect('docs', 'https://gacela-project.com/');
    
    // Matching a route coming from a particular or any custom HTTP methods
    $routes->get('custom', CustomController::class, '__invoke');
    $routes->...('custom', CustomController::class, 'customAction');
    $routes->any('custom', CustomController::class);

    // Matching a route coming from multiple HTTP methods
    $routes->match(['GET', 'POST'], '/', CustomController::class);
    
    // Binding custom dependencies on your controllers
    $routes->get('custom/{number}', CustomControllerWithDependencies::class, 'customAction');
    $bindings->bind(SomeDependencyInterface::class, SomeDependencyConcrete::class)

    // Handle custom Exceptions with class-string|callable
    $handlers->handle(NotFound404Exception::class, NotFound404ExceptionHandler::class);

});

$router->run();

工作演示

要运行工作示例,请运行 composer serve 并检查 example/example.php

提示: composer serve 等同于

php -S localhost:8081 example/example.php