tarikweiss/slim-attribute-router

一个简单的库,用于使用属性进行路由。

0.1.1 2024-09-09 20:05 UTC

This package is auto-updated.

Last update: 2024-09-09 20:05:43 UTC


README

这是一个用于映射路由的属性的小型库。

要求

  • PHP 8.1 或更高版本
  • Slim 4.0 或更高版本

安装

composer require tarikweiss/slim-attribute-router

路由器安装

$router = new \Tarikweiss\SlimAttributeRouter\Router(
    ['/path/to/project/src/Action'],
    new \Tarikweiss\SlimAttributeRouter\PublicMethodRouteTargetCreator('run')
);

/** @var \Slim\App $slimApp */
$router->registerRoutes($slimApp);

路由属性安装

GET 和 POST 方法在类级别安装,PATCH 方法在方法级别安装。

#[\Tarikweiss\SlimAttributeRouter\Route(
    methods: ['GET', 'POST'],
    path: '/foo'
)]
class FooAction
{
    /**
     * Here the name given in the constructor of the PublicMethodRouteTargetCreator is used.
     */
    public function run(
        \Psr\Http\Message\ServerRequestInterface $request,
        \Psr\Http\Message\ResponseInterface      $response,
        array                                    $arguments
    ): \Psr\Http\Message\ResponseInterface {
        // Do you request handling and respond to the request.
        // This structure is given by Slim!
        // Have a look at the docs: https://slim.php.ac.cn/docs/v4/start/installation.html#step-4-hello-world
        return $response;
    }
    
    
    #[\Tarikweiss\SlimAttributeRouter\Route(
        methods: ['PATCH'],
        path: '/foo'
    )]
    public function anotherActionHandler(
        \Psr\Http\Message\ServerRequestInterface $request,
        \Psr\Http\Message\ResponseInterface      $response,
        array                                    $arguments
    ): \Psr\Http\Message\ResponseInterface {
        // Same structure as above, but different scope.
        return $response;
    }
}
}

自定义 RouteTargetCreator

如果您需要为 Slim 的路由注册创建自定义的可调用或可调用字符串,则可以实现 \Tarikweiss\SlimAttributeRouter\RouteTargetCreator 接口。它让您完全控制注册级别(类或方法)以及应注册的类(和方法)。

以下是一个示例实现,用于公共方法的 RouteTargetCreator(随库提供)。

class PublicMethodRouteTargetCreator implements \Tarikweiss\SlimAttributeRouter\RouteTargetCreator
{
    public function __construct(
        public string $classLevelMethodName = 'run'
    )
    {
    }


    public function createRouteTarget(\Tarikweiss\SlimAttributeRouter\RouteLevel $routeLevel, string $class, ?string $method): callable|string
    {
        return match ($routeLevel) {
            \Tarikweiss\SlimAttributeRouter\RouteLevel::LEVEL_CLASS  => $class . ':' . $this->classLevelMethodName,
            \Tarikweiss\SlimAttributeRouter\RouteLevel::LEVEL_METHOD => $class . ':' . $method,
        };
    }
}