辅助函数
可用方法
数组和对象
Arr::accessible()
Arr::accessible
方法用于判断给定的值是否是可通过数组访问的:
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);
// true
$isAccessible = Arr::accessible(new Collection);
// true
$isAccessible = Arr::accessible('abc');
// false
$isAccessible = Arr::accessible(new stdClass);
// false
php
Arr::add()
Arr::add
方法在给定的数组中,如果给定的键不存在或值为 null
,则添加指定的键值对:
use Illuminate\Support\Arr;
$array = Arr::add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
php
Arr::collapse()
Arr::collapse
方法将一个数组的数组合并为一个单一的数组:
use Illuminate\Support\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
php
Arr::crossJoin()
Arr::crossJoin
方法交叉连接给定的数组,返回一个包含所有可能排列的笛卡尔积:
use Illuminate\Support\Arr;
$matrix = Arr::crossJoin([1, 2], ['a', 'b']);
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);
/*
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/
php
Arr::divide()
Arr::divide
方法返回两个数组,一个包含键,另一个包含值:
use Illuminate\Support\Arr;
[$keys, $values] = Arr::divide(['name' => 'Desk']);
// $keys: ['name']
// $values: ['Desk']
php
Arr::dot()
Arr::dot
方法将多维数组扁平化为一个单层数组,并使用 “点” 表示法来表示深度:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = Arr::dot($array);
// ['products.desk.price' => 100]
php
Arr::except()
Arr::except
方法从数组中移除指定的键值对:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$filtered = Arr::except($array, ['price']);
// ['name' => 'Desk']
php
Arr::exists()
Arr::exists
方法检查指定的键是否存在于给定的数组中:
use Illuminate\Support\Arr;
$array = ['name' => 'John Doe', 'age' => 17];
$exists = Arr::exists($array, 'name');
// true
$exists = Arr::exists($array, 'salary');
// false
php
Arr::first()
Arr::first
方法返回通过给定条件测试的数组中的第一个元素:
use Illuminate\Support\Arr;
$array = [100, 200, 300];
$first = Arr::first($array, function (int $value, int $key) {
return $value >= 150;
});
// 200
php
你还可以传递一个默认值作为第三个参数,如果没有值通过测试条件,则返回该默认值:
use Illuminate\Support\Arr;
$first = Arr::first($array, $callback, $default);
php
Arr::flatten()
Arr::flatten
方法将多维数组扁平化为一个单层数组:
use Illuminate\Support\Arr;
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = Arr::flatten($array);
// ['Joe', 'PHP', 'Ruby']
php
Arr::forget()
Arr::forget
方法使用 “点” 表示法从深层嵌套的数组中移除给定的键值对:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::forget($array, 'products.desk');
// ['products' => []]
php
Arr::get()
Arr::get
方法通过 “点” 表示法从深层嵌套的数组中获取值:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$price = Arr::get($array, 'products.desk.price');
// 100
php
Arr::get
方法也接受一个默认值,如果指定的键不存在,则返回该默认值:
use Illuminate\Support\Arr;
$discount = Arr::get($array, 'products.desk.discount', 0);
// 0
php
Arr::has()
Arr::has
方法检查给定的项是否存在于数组中,支持 “点” 表示法:
use Illuminate\Support\Arr;
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = Arr::has($array, 'product.name');
// true
$contains = Arr::has($array, ['product.price', 'product.discount']);
// false
php
Arr::hasAny()
Arr::hasAny
方法检查数组中的任何项是否存在,支持 “点” 表示法:
use Illuminate\Support\Arr;
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = Arr::hasAny($array, 'product.name');
// true
$contains = Arr::hasAny($array, ['product.name', 'product.discount']);
// true
$contains = Arr::hasAny($array, ['category', 'product.discount']);
// false
php
Arr::isAssoc()
Arr::isAssoc
方法判断给定的数组是否为关联数组。如果数组的键不是从零开始的顺序整数,则被认为是关联数组:
use Illuminate\Support\Arr;
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
// true
$isAssoc = Arr::isAssoc([1, 2, 3]);
// false
php
Arr::isList()
Arr::isList
方法判断给定的数组是否为列表数组。一个数组如果其键是从零开始的顺序整数,则被认为是列表数组:
use Illuminate\Support\Arr;
$isList = Arr::isList(['foo', 'bar', 'baz']);
// true
$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);
// false
php
Arr::join()
Arr::join
方法将数组的元素使用指定的字符串连接起来。如果需要,第二个参数可指定连接最后一个元素的分隔符:
use Illuminate\Support\Arr;
$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];
$joined = Arr::join($array, ', ');
// Tailwind, Alpine, Laravel, Livewire
$joined = Arr::join($array, ', ', ' and ');
// Tailwind, Alpine, Laravel and Livewire
php
Arr::keyBy()
Arr::keyBy
方法根据给定的键对数组进行键值化。如果多个项有相同的键,只有最后一个会出现在新数组中:
use Illuminate\Support\Arr;
$array = [
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
];
$keyed = Arr::keyBy($array, 'product_id');
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
php
数字
Number::abbreviate()
Number::abbreviate
方法返回所提供数字值的人类可读格式,并为单位添加缩写:
use Illuminate\Support\Number;
$number = Number::abbreviate(1000);
// 1K
$number = Number::abbreviate(489939);
// 490K
$number = Number::abbreviate(1230000, precision: 2);
// 1.23M
php
Number::clamp()
Number::clamp
方法确保给定的数字保持在指定的范围内。如果数字低于最小值,则返回最小值;如果数字高于最大值,则返回最大值:
use Illuminate\Support\Number;
$number = Number::clamp(105, min: 10, max: 100);
// 100
$number = Number::clamp(5, min: 10, max: 100);
// 10
$number = Number::clamp(10, min: 10, max: 100);
// 10
$number = Number::clamp(20, min: 10, max: 100);
// 20
php
Number::currency()
Number::currency
方法返回给定值的货币表示形式作为字符串:
use Illuminate\Support\Number;
$currency = Number::currency(1000);
// $1,000.00
$currency = Number::currency(1000, in: 'EUR');
// €1,000.00
$currency = Number::currency(1000, in: 'EUR', locale: 'de');
// 1.000,00 €
php
Number::defaultCurrency()
Number::defaultCurrency
方法返回 Number
类使用的默认货币:
use Illuminate\Support\Number;
$currency = Number::defaultCurrency();
// USD
php
Number::defaultLocale()
Number::defaultLocale
方法返回 Number
类使用的默认区域设置:
use Illuminate\Support\Number;
$locale = Number::defaultLocale();
// en
php
Number::fileSize()
Number::fileSize
方法返回给定字节值的文件大小表示形式作为字符串:
use Illuminate\Support\Number;
$size = Number::fileSize(1024);
// 1 KB
$size = Number::fileSize(1024 * 1024);
// 1 MB
$size = Number::fileSize(1024, precision: 2);
// 1.00 KB
php
Number::forHumans()
Number::forHumans
方法返回提供的数值的人类可读格式:
use Illuminate\Support\Number;
$number = Number::forHumans(1000);
// 1 thousand
$number = Number::forHumans(489939);
// 490 thousand
$number = Number::forHumans(1230000, precision: 2);
// 1.23 million
php
Number::format()
Number::format
方法将给定数字格式化为特定区域设置的字符串:
use Illuminate\Support\Number;
$number = Number::format(100000);
// 100,000
$number = Number::format(100000, precision: 2);
// 100,000.00
$number = Number::format(100000.123, maxPrecision: 2);
// 100,000.12
$number = Number::format(100000, locale: 'de');
// 100.000
php
Number::ordinal()
Number::ordinal
方法返回数字的序数形式:
use Illuminate\Support\Number;
$number = Number::ordinal(1);
// 1st
$number = Number::ordinal(2);
// 2nd
$number = Number::ordinal(21);
// 21st
php
Number::pairs()
Number::pairs
方法根据指定的范围和步长生成一个数字对(子范围)数组。此方法对于将更大的数字范围划分为较小的、可管理的子范围(如分页或批处理任务)非常有用。该方法返回一个数组,其中每个内部数组表示一个数字对(子范围):
use Illuminate\Support\Number;
$result = Number::pairs(25, 10);
// [[1, 10], [11, 20], [21, 25]]
$result = Number::pairs(25, 10, offset: 0);
// [[0, 10], [10, 20], [20, 25]]
php
Number::percentage()
Number::percentage
方法返回给定值的百分比表示形式作为字符串:
use Illuminate\Support\Number;
$percentage = Number::percentage(10);
// 10%
$percentage = Number::percentage(10, precision: 2);
// 10.00%
$percentage = Number::percentage(10.123, maxPrecision: 2);
// 10.12%
$percentage = Number::percentage(10, precision: 2, locale: 'de');
// 10,00%
php
Number::spell()
Number::spell
方法将给定数字转换为单词形式:
use Illuminate\Support\Number;
$number = Number::spell(102);
// one hundred and two
$number = Number::spell(88, locale: 'fr');
// quatre-vingt-huit
php
after
参数允许你指定一个值,该值之后所有数字都应该拼写出来:
$number = Number::spell(10, after: 10);
// 10
$number = Number::spell(11, after: 10);
// eleven
php
until
参数允许你指定一个值,该值之前所有数字都应该拼写出来:
$number = Number::spell(5, until: 10);
// five
$number = Number::spell(10, until: 10);
// 10
php
Number::trim()
Number::trim
方法删除给定数字的小数点后多余的零:
use Illuminate\Support\Number;
$number = Number::trim(12.0);
// 12
$number = Number::trim(12.30);
// 12.3
php
Number::useLocale()
Number::useLocale
方法全局设置默认数字区域设置,这会影响后续调用 Number
类方法时数字和货币的格式:
use Illuminate\Support\Number;
/**
* 启动应用服务。
*/
public function boot(): void
{
Number::useLocale('de');
}
php
Number::withLocale()
Number::withLocale
方法使用指定的区域设置执行给定的闭包,然后在回调执行完毕后恢复原始区域设置:
use Illuminate\Support\Number;
$number = Number::withLocale('de', function () {
return Number::format(1500);
});
php
路径(paths)
app_path()
app_path
函数返回你应用程序 app
目录的完整路径。你还可以使用 app_path
函数生成相对于应用程序目录的文件的完整路径:
$path = app_path();
$path = app_path('Http/Controllers/Controller.php');
php
base_path()
base_path
函数返回你应用程序根目录的完整路径。你还可以使用 base_path
函数生成相对于项目根目录的文件的完整路径:
$path = base_path();
$path = base_path('vendor/bin');
php
config_path()
config_path
函数返回你应用程序 config
目录的完整路径。你还可以使用 config_path
函数生成相对于应用程序配置目录的文件的完整路径:
$path = config_path();
$path = config_path('app.php');
php
database_path()
database_path
函数返回你应用程序 database
目录的完整路径。你还可以使用 database_path
函数生成相对于数据库目录的文件的完整路径:
$path = database_path();
$path = database_path('factories/UserFactory.php');
php
lang_path()
lang_path
函数返回你应用程序 lang
目录的完整路径。你还可以使用 lang_path
函数生成相对于该目录的文件的完整路径:
$path = lang_path();
$path = lang_path('en/messages.php');
php
默认情况下,Laravel 应用程序框架并不包含 |
public_path()
public_path
函数返回你应用程序 public
目录的完整路径。你还可以使用 public_path
函数生成相对于 public
目录的文件的完整路径:
$path = public_path();
$path = public_path('css/app.css');
php
URLs
action()
action
函数为给定的控制器动作生成一个 URL:
use App\Http\Controllers\HomeController;
$url = action([HomeController::class, 'index']);
php
如果该方法需要路由参数,可以作为第二个参数传递给该方法:
$url = action([UserController::class, 'profile'], ['id' => 1]);
php
asset()
asset
函数使用当前请求的协议(HTTP 或 HTTPS)生成资产的 URL:
$url = asset('img/photo.jpg');
php
你可以通过在 .env
文件中设置 ASSET_URL
变量来配置资产 URL 主机。如果你将资产托管在像 Amazon S3 或其他 CDN 之类的外部服务上,这将非常有用:
// ASSET_URL=http://example.com/assets
env
$url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg
php
route()
route
函数为给定的命名路由生成一个 URL:
$url = route('route.name');
php
如果路由需要参数,你可以作为第二个参数传递它们:
$url = route('route.name', ['id' => 1]);
php
默认情况下,route
函数生成的是绝对 URL。如果你希望生成相对 URL,可以作为第三个参数传递 false
:
$url = route('route.name', ['id' => 1], false);
php
secure_url()
secure_url
函数为给定的路径生成一个完全合格的 HTTPS URL。可以在函数的第二个参数中传递额外的 URL 段:
$url = secure_url('user/profile');
$url = secure_url('user/profile', [1]);
php
混合
abort()
abort
函数抛出一个 【HTTP 异常】,该异常将由【异常处理程序】渲染:
abort(403);
php
您还可以提供异常的消息和要发送到浏览器的自定义 HTTP 响应头:
abort(403, 'Unauthorized.', $headers);
php
abort_if()
abort_if
函数如果给定的布尔表达式求值为 true
,则抛出 HTTP 异常:
abort_if(! Auth::user()->isAdmin(), 403);
php
与 abort
方法类似,您还可以提供异常的响应文本作为第三个参数,并将自定义响应头作为第四个参数传递给该函数。
abort_unless()
abort_unless
函数如果给定的布尔表达式求值为 false
,则抛出 HTTP 异常:
abort_unless(Auth::user()->isAdmin(), 403);
php
与 abort
方法类似,您还可以提供异常的响应文本作为第三个参数,并将自定义响应头作为第四个参数传递给该函数。
auth()
auth
函数返回一个【认证】实例。您可以将其用作 Auth
门面的替代品:
$user = auth()->user();
php
如果需要,您可以指定要访问的 guard 实例:
$user = auth('admin')->user();
php
back()
back
函数生成一个【重定向 HTTP 响应】到用户的上一个位置:
return back($status = 302, $headers = [], $fallback = '/');
return back();
php
bcrypt()
bcrypt
函数使用 Bcrypt 哈希给定的值。您可以将此函数用作 Hash
门面的替代品:
$password = bcrypt('my-secret-password');
php
blank()
blank
函数确定给定的值是否为 “空”:
blank('');
blank(' ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
// false
php
要查看 blank
的反面,请查看 filled
方法。
broadcast()
broadcast(new UserRegistered($user));
broadcast(new UserRegistered($user))->toOthers();
php
cache()
cache
函数可用于从 【缓存】 中获取值。如果给定的键在缓存中不存在,将返回一个可选的默认值:
$value = cache('key');
$value = cache('key', 'default');
php
您可以通过传递一个键值对数组将项添加到缓存。还应传递缓存值应被视为有效的秒数或持续时间:
cache(['key' => 'value'], 300);
cache(['key' => 'value'], now()->addSeconds(10));
php
class_uses_recursive()
class_uses_recursive
函数返回一个类使用的所有 trait,包括它所有父类使用的 trait:
$traits = class_uses_recursive(App\Models\User::class);
php
config()
config
函数获取【配置】变量的值。配置值可以使用 “点” 语法访问,其中包括文件名和您希望访问的选项。如果配置选项不存在,可以指定默认值:
$value = config('app.timezone');
$value = config('app.timezone', $default);
php
您可以通过传递一个键值对数组在运行时设置配置变量。但请注意,此方法仅影响当前请求的配置值,并不会更新实际的配置文件值:
config(['app.debug' => true]);
php
context()
context
函数获取【当前上下文】的值。如果上下文键不存在,可以返回一个默认值:
$value = context('trace_id');
$value = context('trace_id', $default);
php
您可以通过传递一个键值对数组设置上下文值:
use Illuminate\Support\Str;
context(['trace_id' => Str::uuid()->toString()]);
php
dd()
dd
函数输出给定的变量,并终止脚本执行:
dd($value); dd($value1, $value2, $value3, ...);
php
如果您不想终止脚本执行,可以改用 dump
函数。
dump()
dump
函数输出给定的变量:
dump($value); dump($value1, $value2, $value3, ...);
php
如果您希望在输出变量后停止执行脚本,请使用 dd
函数。
env()
env
函数检索【环境变量】的值,或者返回默认值:
$env = env('APP_ENV');
$env = env('APP_ENV', 'production');
php
如果在部署过程中执行了 |
fake()
fake
函数从容器解析一个 【Faker】 单例,这在创建模型工厂、数据库填充、测试和视图原型中创建假数据时非常有用:
@for($i = 0; $i < 10; $i++)
<dl>
<dt>Name</dt>
<dd>{{ fake()->name() }}</dd>
<dt>Email</dt>
<dd>{{ fake()->unique()->safeEmail() }}</dd>
</dl>
@endfor
php
默认情况下,fake
函数将使用 app.faker_locale
配置选项。通常,此配置选项是通过 APP_FAKER_LOCALE
环境变量设置的。您也可以通过传递它到 fake
函数来指定区域设置。
filled()
filled
函数确定给定的值是否不是 “空”:
filled(0);
filled(true);
filled(false);
// true
filled('');
filled(' ');
filled(null);
filled(collect());
// false
php
要查看 filled
的反面,请查看 blank
方法。
info()
info
函数将信息写入应用程序的【日志】:
info('Some helpful information!');
php
您还可以传递一个包含上下文数据的数组:
info('User login attempt failed.', ['id' => $user->id]);
php
literal()
literal
函数创建一个新的 【stdClass】 实例,并将给定的命名参数作为属性:
$obj = literal(
name: 'Joe',
languages: ['PHP', 'Ruby'],
);
$obj->name; // 'Joe'
$obj->languages; // ['PHP', 'Ruby']
php
logger()
logger
函数可用于将 debug
级别消息写入【日志】:
logger('Debug message');
php
您还可以传递一个包含上下文数据的数组:
logger('User has logged in.', ['id' => $user->id]);
php
如果不传递值,【logger】 函数将返回一个 logger 实例:
logger()->error('You are not allowed here.');
php
method_field()
method_field
函数生成一个包含表单 HTTP 动词伪造值的 HTML hidden
输入字段。例如,使用 【Blade 语法】:
<form method="POST">
{{ method_field('DELETE') }}
</form>
php
old()
old()
函数用于【检索】闪存到会话中的【旧输入值】:
$value = old('value');
$value = old('value', 'default');
php
由于提供给 old()
函数的第二个参数通常是一个 Eloquent 模型的属性,Laravel 允许你直接传入整个 Eloquent 模型作为第二个参数。当这样做时,Laravel 会假设第一个参数是 Eloquent 属性的名称,并将其作为 “默认值”:
{{ old('name', $user->name) }}
// 等同于...
{{ old('name', $user) }}
php
once()
once()
函数执行给定的回调,并将结果缓存到内存中,直到请求结束。任何后续调用相同回调的 once()
函数都将返回先前缓存的结果:
function random(): int
{
return once(function () {
return random_int(1, 1000);
});
}
random(); // 123
random(); // 123 (缓存的结果)
random(); // 123 (缓存的结果)
php
当 once()
函数在对象实例中执行时,缓存的结果将对该对象实例唯一:
<?php
class NumberService
{
public function all(): array
{
return once(fn () => [1, 2, 3]);
}
}
$service = new NumberService;
$service->all();
$service->all(); // (缓存的结果)
$secondService = new NumberService;
$secondService->all();
$secondService->all(); // (缓存的结果)
php
optional()
optional()
函数接受任何参数,并允许你访问该对象的属性或调用方法。如果传入的对象为 null
,则访问属性和方法时会返回 null
,而不会导致错误:
return optional($user->address)->street;
{!! old('name', optional($user)->name) !!}
php
optional()
函数还接受一个闭包作为第二个参数。如果作为第一个参数提供的值不为 null
,则会调用这个闭包:
return optional(User::find($id), function (User $user) {
return $user->name;
});
php
redirect()
redirect()
函数返回一个【重定向的 HTTP 响应】,如果没有传递任何参数,则返回重定向器实例:
return redirect($to = null, $status = 302, $headers = [], $https = null);
return redirect('/home');
return redirect()->route('route.name');
php
report()
report()
函数使用你的【异常处理器】报告一个异常:
report($e);
php
report
函数也接受一个字符串作为参数。当传入一个字符串时,函数会创建一个异常,并将该字符串作为异常消息:
report('Something went wrong.');
php
report_if()
report_if
函数将在给定条件为 true
时,使用【异常处理器】报告一个异常:
report_if($shouldReport, $e);
report_if($shouldReport, 'Something went wrong.');
php
report_unless()
report_unless
函数将在给定条件为 false
时,使用【异常处理器】报告一个异常:
report_unless($reportingDisabled, $e);
report_unless($reportingDisabled, 'Something went wrong.');
php
request()
request
函数返回当前【请求】实例,或者从当前请求中获取某个输入字段的值:
$request = request();
$value = request('key', $default);
php
rescue()
rescue
函数执行给定的闭包,并捕获执行过程中发生的任何异常。所有捕获的异常都会发送到你的【异常处理器】,但请求仍会继续处理:
return rescue(function () {
return $this->method();
});
php
你也可以向 rescue
函数传递第二个参数。这个参数是如果在执行闭包时发生异常时应返回的 "默认" 值:
return rescue(function () {
return $this->method();
}, false);
return rescue(function () {
return $this->method();
}, function () {
return $this->failure();
});
php
你可以提供一个 report
参数来决定是否通过 report
函数报告异常:
return rescue(function () {
return $this->method();
}, report: function (Throwable $throwable) {
return $throwable instanceof InvalidArgumentException;
});
php
response()
response
函数创建一个【响应】实例,或者获取响应工厂的实例:
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);
php
retry()
retry
函数尝试执行给定的回调,直到达到给定的最大尝试次数。如果回调没有抛出异常,则返回回调的返回值。如果回调抛出异常,则会自动重试。如果超过最大尝试次数,则抛出异常:
return retry(5, function () {
// 尝试5次,每次尝试之间休息100毫秒...
}, 100);
php
如果你希望手动计算每次尝试之间的休眠时间,可以将一个闭包作为第三个参数传递给 retry
函数:
use Exception;
return retry(5, function () {
// ...
}, function (int $attempt, Exception $exception) {
return $attempt * 100;
});
php
为了方便起见,你可以将一个数组作为 retry
函数的第一个参数。这个数组将用来决定每次尝试之间休眠多少毫秒:
return retry([100, 200], function () {
// 第一次重试休眠100毫秒,第二次重试休眠200毫秒...
});
php
如果你只希望在特定条件下重试,可以将一个闭包作为第四个参数传递给 retry
函数:
use Exception;
return retry(5, function () {
// ...
}, 100, function (Exception $exception) {
return $exception instanceof RetryException;
});
php
session()
session
函数可以用来获取或设置【会话】值:
$value = session('key');
php
你可以通过传递一个包含键值对的数组来设置值:
session(['chairs' => 7, 'instruments' => 3]);
php
如果没有传递任何值,则会返回会话存储:
$value = session()->get('key');
session()->put('key', $value);
php
tap()
tap
函数接受两个参数:一个任意的 $value
和一个闭包。$value
将被传递给闭包,然后由 tap
函数返回。闭包的返回值不重要:
$user = tap(User::first(), function (User $user) {
$user->name = 'taylor';
$user->save();
});
php
如果没有传递闭包给 tap
函数,你可以在给定的 $value
上调用任何方法。无论该方法实际返回什么值,tap
都会始终返回 $value
。例如,Eloquent 的 update
方法通常返回一个整数。但我们可以通过链式调用 update
方法,使其返回模型本身:
$user = tap($user)->update([
'name' => $name,
'email' => $email,
]);
php
要为类添加 tap
方法,可以将 Illuminate\Support\Traits\Tappable
特性添加到该类中。此特性的 tap
方法只接受一个闭包参数。对象实例本身会被传递给闭包,并由 tap
方法返回:
return $user->tap(function (User $user) {
// ...
});
php
throw_if()
throw_if
函数会在给定的布尔表达式为 true
时抛出指定的异常:
throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);
throw_if(
! Auth::user()->isAdmin(),
AuthorizationException::class,
'You are not allowed to access this page.'
);
php
throw_unless()
throw_unless
函数会在给定的布尔表达式为 false
时抛出指定的异常:
throw_unless(Auth::user()->isAdmin(), AuthorizationException::class);
throw_unless(
Auth::user()->isAdmin(),
AuthorizationException::class,
'You are not allowed to access this page.'
);
php
trait_uses_recursive()
trait_uses_recursive
函数返回某个特性所使用的所有特性:
$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);
php
transform()
transform
函数会在给定的值不是【空值】时执行一个闭包,然后返回闭包的返回值:
$callback = function (int $value) {
return $value * 2;
};
$result = transform(5, $callback);
// 10
php
可以将一个默认值或闭包作为第三个参数传递给函数。如果给定的值为空,则返回该默认值或闭包的返回值:
$result = transform(null, $callback, 'The value is blank');
// The value is blank
php
validator()
validator
函数使用给定的参数创建一个新的【验证器】实例。你可以使用它作为 Validator
facade 的替代方法:
$validator = validator($data, $rules, $messages);
php
value()
value
函数返回它接收到的值。然而,如果你传递一个闭包给该函数,则会执行该闭包,并返回闭包的返回值:
$result = value(true);
// true
$result = value(function () {
return false;
});
// false
php
你可以向 value
函数传递额外的参数。如果第一个参数是一个闭包,那么额外的参数会作为参数传递给闭包,否则这些参数会被忽略:
$result = value(function (string $name) {
return $name;
}, 'Taylor');
// 'Taylor'
php
其它工具
基准测试
有时你可能希望快速测试应用程序某些部分的性能。在这种情况下,你可以使用 Benchmark
支持类来测量给定回调完成所需的毫秒数:
<?php
use App\Models\User;
use Illuminate\Support\Benchmark;
Benchmark::dd(fn () => User::find(1)); // 0.1 ms
Benchmark::dd([
'Scenario 1' => fn () => User::count(), // 0.5 ms
'Scenario 2' => fn () => User::all()->count(), // 20.0 ms
]);
php
默认情况下,给定的回调将执行一次(一次迭代),并且它们的持续时间将在浏览器或控制台中显示。
要多次调用回调,你可以将回调执行的次数作为第二个参数传递给方法。当回调执行多次时,Benchmark
类将返回回调在所有迭代中执行的平均毫秒数:
Benchmark::dd(fn () => User::count(), iterations: 10); // 0.5 ms
php
有时,你可能希望在基准测试回调执行时间的同时,还能获取回调返回的值。value
方法将返回一个元组,包含回调返回的值和执行回调所需的毫秒数:
[$count, $duration] = Benchmark::value(fn () => User::count());
php
日期
Laravel 包含了 Carbon,这是一个强大的日期和时间处理库。你可以通过调用 now
函数来创建一个新的 Carbon 实例。这个函数在你的 Laravel 应用中是全局可用的:
$now = now();
php
或者,你也可以使用 Illuminate\Support\Carbon
类来创建一个新的 Carbon 实例:
use Illuminate\Support\Carbon;
$now = Carbon::now();
php
关于 Carbon 及其功能的详细讨论,请参考【官方的 Carbon 文档】。
延迟函数
延迟函数目前处于测试版阶段,我们正在收集社区反馈。 |
尽管 Laravel 的【队列任务】允许你将任务放入后台处理,但有时你可能希望延迟执行一些简单的任务,而不需要配置或维护一个长时间运行的队列工作者。
延迟函数允许你将闭包的执行延迟到 HTTP 响应发送给用户之后,这样可以保持应用程序的快速响应。要延迟执行一个闭包,只需将闭包传递给 Illuminate\Support\defer
函数:
use App\Services\Metrics;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use function Illuminate\Support\defer;
Route::post('/orders', function (Request $request) {
// 创建订单...
defer(fn () => Metrics::reportOrder($order));
return $order;
});
php
默认情况下,只有在调用 Illuminate\Support\defer
的 HTTP 响应、Artisan 命令或队列任务成功完成后,延迟函数才会被执行。这意味着,如果请求返回 4xx
或 5xx
错误响应,延迟函数将不会执行。如果你希望延迟函数始终执行,可以在延迟函数上链式调用 always
方法:
defer(fn () => Metrics::reportOrder($order))->always();
php
取消延迟函数
如果你需要在延迟函数执行之前取消它,可以使用 forget
方法通过名称取消函数。要为延迟函数命名,提供 Illuminate\Support\defer
函数的第二个参数:
defer(fn () => Metrics::report(), 'reportMetrics');
defer()->forget('reportMetrics');
php
延迟函数兼容性
如果你从 Laravel 10.x 升级到 Laravel 11.x,并且你的应用程序骨架中仍然包含 app/Http/Kernel.php
文件,你应该将 InvokeDeferredCallbacks
中间件添加到内核的 $middleware
属性的开头:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class,
\App\Http\Middleware\TrustProxies::class,
// ...
];
php
在测试中禁用延迟函数
编写测试时,禁用延迟函数可能会很有用。你可以在测试中调用 withoutDefer
来指示 Laravel 立即执行所有延迟函数:
test('without defer', function () {
$this->withoutDefer();
// ...
});
php
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_without_defer(): void
{
$this->withoutDefer();
// ...
}
}
php
如果你希望在整个测试用例中禁用所有延迟函数,可以在基类 TestCase
的 setUp
方法中调用 withoutDefer
方法:
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->withoutDefer();
}
}
php
抽奖
Laravel 的 Lottery
类可以根据给定的概率执行回调。这在你只希望在一定比例的请求中执行代码时特别有用:
use Illuminate\Support\Lottery;
Lottery::odds(1, 20)
->winner(fn () => $user->won())
->loser(fn () => $user->lost())
->choose();
php
你可以将 Laravel 的 Lottery
类与其他 Laravel 功能结合使用。例如,你可能只希望将少量的慢查询报告到异常处理程序中。由于 Lottery
类是可调用的,我们可以将其实例传递给任何接受可调用方法的函数:
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Lottery;
DB::whenQueryingForLongerThan(
CarbonInterval::seconds(2),
Lottery::odds(1, 100)->winner(fn () => report('Querying > 2 seconds.')),
);
php
管道
Laravel 的 Pipeline
facade 提供了一种方便的方法,可以将给定的输入通过一系列可调用的类、闭包或回调 “管道”,让每个类有机会检查或修改输入,并调用管道中的下一个可调用函数:
use Closure;
use App\Models\User;
use Illuminate\Support\Facades\Pipeline;
$user = Pipeline::send($user)
->through([
function (User $user, Closure $next) {
// ...
return $next($user);
},
function (User $user, Closure $next) {
// ...
return $next($user);
},
])
->then(fn (User $user) => $user);
php
如你所见,管道中的每个可调用类或闭包都会收到输入和一个 $next
闭包。调用 $next
闭包会调用管道中的下一个可调用函数。正如你可能注意到的,这与中间件非常相似。
当管道中的最后一个可调用函数调用 $next
闭包时,传递给 then
方法的可调用函数会被执行。通常,这个可调用函数只是简单地返回给定的输入。
当然,正如前面讨论的,你不仅限于向管道提供闭包。你还可以提供可调用类。如果提供了类名,Laravel 的【服务容器】将实例化该类,并注入其依赖:
$user = Pipeline::send($user) ->through([ GenerateProfilePhoto::class, ActivateSubscription::class, SendWelcomeEmail::class, ]) ->then(fn (User $user) => $user);
php
睡眠
Laravel 的 Sleep
类是对 PHP 本地的 sleep
和 usleep
函数的轻量级封装,提供了更好的可测试性,并且暴露了一个开发者友好的 API 来处理时间操作:
use Illuminate\Support\Sleep;
$waiting = true;
while ($waiting) {
Sleep::for(1)->second();
$waiting = /* ... */;
}
php
Sleep
类提供了多种方法,允许你使用不同的时间单位进行操作:
// 在休眠后返回一个值...
$result = Sleep::for(1)->second()->then(fn () => 1 + 1);
// 在给定值为 true 时休眠...
Sleep::for(1)->second()->while(fn () => shouldKeepSleeping());
// 暂停执行 90 秒...
Sleep::for(1.5)->minutes();
// 暂停执行 2 秒...
Sleep::for(2)->seconds();
// 暂停执行 500 毫秒...
Sleep::for(500)->milliseconds();
// 暂停执行 5000 微秒...
Sleep::for(5000)->microseconds();
// 暂停执行直到指定时间...
Sleep::until(now()->addMinute());
// PHP 原生 "sleep" 函数的别名...
Sleep::sleep(2);
// PHP 原生 "usleep" 函数的别名...
Sleep::usleep(5000);
php
你可以使用 and
方法轻松地将多个时间单位组合起来:
Sleep::for(1)->second()->and(10)->milliseconds();
php
测试 Sleep
在测试使用 Sleep
类或 PHP 原生 sleep
函数的代码时,测试会暂停执行。这会让你的测试套件变得非常慢。例如,假设你正在测试以下代码:
$waiting = /* ... */;
$seconds = 1;
while ($waiting) {
Sleep::for($seconds++)->seconds();
$waiting = /* ... */;
}
php
通常,测试这段代码至少需要一秒钟。幸运的是,Sleep
类允许我们“伪造”休眠,以保持测试套件的速度:
it('waits until ready', function () {
Sleep::fake();
// ...
});
php
public function test_it_waits_until_ready()
{
Sleep::fake();
// ...
}
php
当伪造 Sleep
类时,实际的执行暂停会被绕过,测试会大大加快。
一旦伪造了 Sleep
类,可以对预期的 “休眠” 进行断言。假设我们正在测试的代码会暂停执行三次,每次暂停时间增加一秒。我们可以使用 assertSequence
方法,断言我们的代码是否 “正确地” 休眠了,同时保持测试快速:
it('checks if ready three times', function () {
Sleep::fake();
// ...
Sleep::assertSequence([
Sleep::for(1)->second(),
Sleep::for(2)->seconds(),
Sleep::for(3)->seconds(),
]);
}
php
public function test_it_checks_if_ready_three_times()
{
Sleep::fake();
// ...
Sleep::assertSequence([
Sleep::for(1)->second(),
Sleep::for(2)->seconds(),
Sleep::for(3)->seconds(),
]);
}
php
当然,Sleep
类还提供了多种其他断言方法,供你在测试时使用:
use Carbon\CarbonInterval as Duration;
use Illuminate\Support\Sleep;
// Assert that sleep was called 3 times...
Sleep::assertSleptTimes(3);
// Assert against the duration of sleep...
Sleep::assertSlept(function (Duration $duration): bool {
return /* ... */;
}, times: 1);
// Assert that the Sleep class was never invoked...
Sleep::assertNeverSlept();
// Assert that, even if Sleep was called, no execution paused occurred...
Sleep::assertInsomniac();
php
有时,你可能希望在应用代码中每次伪造休眠时执行某个操作。你可以通过 whenFakingSleep
方法提供一个回调来实现这一点。在以下示例中,我们使用 Laravel 的时间操作助手函数来瞬间推进时间,按每次休眠的持续时间:
use Carbon\CarbonInterval as Duration;
$this->freezeTime();
Sleep::fake();
Sleep::whenFakingSleep(function (Duration $duration) {
// 伪造休眠时推进时间...
$this->travel($duration->totalMilliseconds)->milliseconds();
});
php
由于推进时间是常见需求,fake
方法接受 syncWithCarbon
参数,以便在测试中保持 Carbon 的同步:
Sleep::fake(syncWithCarbon: true);
$start = now();
Sleep::for(1)->second();
$start->diffForHumans(); // 1 second ago
php
Laravel 在内部使用 Sleep
类来暂停执行。例如,retry
辅助函数在休眠时使用 Sleep
类,这使得在使用该辅助函数时,可以更容易地进行测试。