tyler36 / laravel-helper-macros
该软件包最新版本(1.0.1)没有可用的许可证信息。
Laravel的辅助函数和宏集合
1.0.1
2016-12-02 06:52 UTC
Requires (Dev)
- phpunit/phpunit: ^5.4
- squizlabs/php_codesniffer: ^2.6
This package is auto-updated.
Last update: 2024-09-28 06:02:18 UTC
README
安装
1. 通过composer安装软件包。
composer require tyler36/laravel-helper-macros
2. 将软件包添加到config/app.php
Tyler36\laravelHelpers\LaravelHelperServiceProvider::class,
辅助函数
验证器
受Validate (almost) anything in Laravel的启发。使用Laravel验证器类进行验证。
示例:验证日期(期望FALSE)
tyler36\laravelHelpers\Helper::validate('20150230', 'date');
示例:验证日期(期望TRUE)
tyler36\laravelHelpers\Helper::validate('20150230', 'date');
宏
集合
这些宏扩展了集合功能。
管道
受The pipe collection macro的启发。将集合传递给一个函数。
$collect = collect([1, 2, 3])
->pipe(function ($data) {
return $data->merge([4, 5, 6]);
});
dd
受Debugging collections的启发。通过'dump and die'当前状态来调试集合。可以在链式调用中用于中断和转储。
collect($items)
->filter(function() {
...
})
->dd()
ifEmpty
如果集合为空,则运行回调函数。
$items = collect([]);
$items->ifEmpty(function(){
abort(500, 'No items');
});
ifAny
如果集合有数据(>1项),则运行回调函数。
$errors = collect(['Something went wrong']);
$errors->ifAny(function(){
abort(500, 'There was at-least 1 problem');
});
mapToAssoc
将集合转换为关联数组,受Customizing Keys When Mapping Collections的启发。
$emailLookup = $employees->mapToAssoc(function ($employee) {
return [$employee['email'], $employee['name']];
});
响应
这些宏有助于在整个应用程序中标准化API JSON响应的返回。受Laravel Response Macros for APIs的启发。
成功
返回带有HTTP状态码200的有效载荷($data)
response()->success($data);
示例:
response()->success(['earth' => 3, 'sun' => 'yellow'])
返回以下内容的HTTP状态200
{"errors":false,"data":{"earth":3,"sun":"yellow"}}
无内容
返回空内容,带有HTTP状态码204
response()->noContent()
错误
返回消息($message)内容,并可选地返回HTTP状态码($statusCode)[默认:HTTP状态码400]
response()->error($message);
示例:
response()->error('There was an error.');
返回以下内容的HTTP状态400
{"errors":true,"message":"There was an error."}
示例:
response()->error('Not authorized!', 403);
返回以下内容的HTTP状态403
{"errors":true,"message":"Not authorized!"}