giacomofurlan / slim3annotation-router
允许通过 @Route(...) 注解定义路由
v1.0.2
2016-06-12 23:50 UTC
Requires
- php: >=5.6.6
- slim/slim: ^3.0
This package is auto-updated.
Last update: 2024-09-09 13:32:34 UTC
README
由 Giacomo Furlan 提供
这个库允许在 Slim3 中使用注解来定义路由,而不是通过程序定义(类似于 Symfony 的方式)。
这是基于 GNU GPL v3 的免费软件。有关更多信息,请参阅许可文件。
支持的语法
/**
* @Route("/class/route/prefix")
*/
class MyController {
/**
* @Route("/path/{arg}/{arg2}", name="route.name" methods=["GET", "POST"])
*/
public function myAction(ServerRequestInterface $request, ResponseInterface $response, $arg1, $arg2)
{ ... }
}
规则
- 控制器类的名称必须以 "Controller" 后缀结尾,例如
MyTestController
。 - 控制器构造函数只能有
App
或ContainerInterface
依赖。 @Route
注解至少需要路由(第一个参数用引号括起来)- 类可以只有
@Route
注解,指定整个类的操作的唯一前缀 - 方法可以指定
@Route
注解。可选值包括:name
: 路由名称(以便在其他地方调用)methods
: 指定动作响应的方法。默认:全部
- 方法可以指定路由中写入的任何参数(作为占位符),并按名称映射,区分大小写。这意味着如果存在路由占位符
{myArgument}
,则可能有方法参数$myArgument
。如果有名为$myArgument
的方法参数,则必须有{myArgument}
路由占位符。例外是ServerRequestInterface
、ResponseInterface
和ContainerInterface
参数,它们可以以任何变量名调用,并且总是标准$request
、$response
和$app->getContainer()
Slim3 对象。
设置
<?php
use giacomofurlan\slim3AnnotationRouter\Router;
# include your autoload
$app = new \Slim\App(...);
# define variables
new Router($app, $controllersDirectory, $globalRoutePrefix, $cacheDir);
$app->run();
$controllersDirectory
可以是字符串或字符串数组。因此,如果需要,可以定义多个控制器目录。子目录将自动扫描。
$globalRoutePrefix
是可选的,默认 ''
。如果设置,全局路由前缀将应用于所有解析的路由。
$cacheDir
是可选的,默认 null
。如果设置,将生成缓存文件,因此当应用程序第二次加载时,它不需要再次扫描目录,从而避免反射类。每次控制器文件被修改时,都会重新写入缓存。