fran-f / yolk
Yolk 是一个用于小型项目的玩具框架。
1.0.0
2022-05-31 22:45 UTC
Requires
- php: >=7.4
Requires (Dev)
- pestphp/pest: ^1.21
- phpstan/phpstan: ^1.4
- squizlabs/php_codesniffer: ^3.4
README
Yolk 是一个针对 Apache 下运行的 PHP 应用程序的轻量级路由+调度库。
- 路由到控制器
- 请求预处理器(中间件)
- 结构化访问请求参数
- 友好语法的常见响应
- 命名路由的路径生成
- 错误页面和异常处理
- 支持依赖注入
示例前端控制器
<?php require 'vendor/autoload.php'; $app = new Yolk\App('https://example.com/'); $app->routes() ->get('/', HomeController::class) ->get('/admin', AdminController::class) ->get('/login', LoginController::class, 'login_page') ->post('/login', AuthenticateUser::class); $app->routes() ->error(404, NotFoundController::class); $app->middleware() ->only('/admin|/admin/.*', RequireLogin::class); $app->renderViewsWith( fn($view, $data) => (new Twig\Engine)->render($view, $data)) ); $app->run()->output;
示例路由控制器
<?php use Yolk\Request; class HomeController { public function __invoke(Request $request) { return [ 'user' => Session::getLoggedInUser(), 'articles' => Blog::getRecent(), ]; } }
请求参数
控制器通过单个参数调用,该参数是一个 Yolk\Request
实例,它封装了所有请求参数,按优先级顺序:路由元素、查询字符串(GET)和表单参数(POST)。
请求对象可以像数组一样访问。缺失的参数将具有 null
值。
$email = $request['email'];
《optional()`》和《required()`》方法支持同时访问多个参数。如果《required()`》参数缺失,Yolk 将立即返回一个 400 响应。
list($name, $surname) = $request->required('name', 'surname'); # returns a single value $phone = $request->optional('phone'); # returns an array $address = $request->optional('address1', 'address2', 'address3'); # returns an associative array $address = $request->optional([ 'address1', 'address2', 'address3' ]);
《all()`》方法返回所有参数的完整集合。
简短响应
控制器可以返回 Yolk\Response
实例(支持状态码、头信息等),但它们也可以返回快捷值
-
整数用于状态码
return 404;
Yolk 将调用已注册该状态码的错误控制器。如果没有配置控制器,它将渲染一个基本错误页面。
-
字符串用于 302 重定向
# absolute URLs are used as-is return 'https://example.com'; # relative URLs will be prepended with the base URL return '/admin'; # → https://example.com/admin # route names starting with a ':' will be converted return ':login_page'; # → https://example.com/login
-
数组用于渲染默认视图
return [ 'user' => $user, 'balance' => $balance, ];
Yolk 将控制器名称和数组传递给渲染回调函数,该函数可以推导出视图名称并渲染其内容。
中间件
在到达控制器之前,Yolk 可以将 Request
对象传递给一系列预处理器。每个预处理器都可以检查请求,并决定保留其原样并继续链(返回 null
)、替换它(返回新的 Request
)或中断链(返回 Response
)。
可以为所有或部分路由配置预处理器
$app->middleware() ->all(ValidateCsrfToken::class) ->except('/login', RequireAuthentication::class) ->only('/api/.*', EnforceRateLimit::class);
依赖注入
默认情况下,Yolk 创建控制器实例而不传递任何参数。要依赖依赖注入库,请使用《injectWith()`》方法
$app = new Yolk\App('https://example.com/'); $di = new SomeLibrary\DependencyInjection() $app->injectWith(fn($class) => $di->inject($class)); $app->run()->output;