scuttlebyte / laravel-request-context
轻松存储和访问请求上下文数据
v1.0.0
2022-07-31 20:10 UTC
Requires
- php: ^7.3|^8.0
Requires (Dev)
- orchestra/testbench: ^6.19
- phpunit/phpunit: ^9.0
- squizlabs/php_codesniffer: ^3.6
This package is not auto-updated.
Last update: 2024-09-23 06:17:54 UTC
README
此包使管理请求的上下文数据变得轻松。可以将请求上下文视为会话数据的替代品,区别在于请求上下文仅存在于请求的生命周期内。
例如,您可以这样检索已认证的 User
的活动 Team
:
$currentTeam = Request::context()->get('currentTeam');
安装
您可以通过composer安装此包
composer require scuttlebyte/laravel-request-context
注意:需要Laravel 5.4+。
用法
注册上下文以供请求中后续使用
Request::context()->put('currentTeam', Request::user()->teams->first());
通过键访问请求上下文
$currentTeam = Request::context()->get('currentTeam');
请求上下文不必是Eloquent模型
<?php Request::context()->put('currentTeamTaskCount', Request::user()->teams->first()->tasks->count()); $count = Request::context()->get('currentTeamTaskCount'); // int(10)
<?php Request::context()->put('teamOwner', Request::user()->teams->first()->owner->name); $owner = Request::context()->get('teamOwner'); // string(14) "Martha Stewart"
<?php Request::context()->put('teamProperties', Request::user()->teams->first()->properties); $properties = Request::context()->get('teamProperties'); // array(1) { // 'foo' => // string(3) "bar" // }
几乎没有什么限制。您甚至可以传递一个上下文字符数组
<?php Request::context()->put([ 'currentTeamTaskCount' => Request::user()->teams->first()->tasks->count(), 'teamOwner' => Request::user()->teams->first()->owner->name ]); $count = Request::context()->get('currentTeamTaskCount'); // int(10) $owner = Request::context()->get('teamOwner'); // string(14) "Martha Stewart"
外观 & 辅助函数
没关系,这里没有评判。
外观 Context
// store it Context::put('currentTeam', Request::user()->teams->first()); // get it $currentTeam = Context::get('currentTeam');
辅助方法 context()
// store it context('currentTeam', request()->user()->teams->first()); // get it $currentTeam = context('currentTeam');
在哪里绑定上下文?
中间件是完美的候选人
<?php namespace App\Http\Middleware; use Closure; class StoreTeamRequestContext { public function handle($request, Closure $next) { $request->context()->put('currentTeam', $request->user()->teams()->first()); return $next($request); } }
但为什么呢?
通过链式Eloquent关系和辅助函数访问上下文数据会导致在您的应用程序中泄露实现细节,并且通常会导致许多类似和重复的代码行。
此包将尽力在以下方面帮助您:
- 在单个位置显式绑定上下文数据
- 使重构上下文关系变得更容易且风险更低
- 在您能够访问到
Request
对象的地方轻松检索上下文值,而无需记住链式Eloquent关系
测试
composer test
变更日志
请参阅变更日志了解最近更改的更多信息。
贡献
请参阅贡献指南了解详细信息。
安全
如果您发现任何与安全相关的问题,请通过电子邮件jake@scuttlebyte.com联系,而不是使用问题跟踪器。
鸣谢
Spatie 对开源和Laravel社区的贡献(以及用于创建此包的骨架!)
许可
MIT许可(MIT)。请参阅许可文件获取更多信息。