jralph / retry
一个简单的重试库。
3.0.0
2023-07-31 11:59 UTC
Requires
- php: ^8.0
Requires (Dev)
- phpspec/phpspec: ^7.4
README
一个简单的PHP命令重试库。
安装
此包通过composer提供。
composer require jralph/retry
基本用法
库包含一个简单的辅助函数,方便使用。
注意:如果命令执行失败,则会抛出 Jralph\Retry\RetryException
。
mixed retry (int|callable $attempts , callable $command [, callable $onError = null])
参数
$attempts:
尝试执行命令的次数。- 如果提供了一个
callable
,则重试会继续进行,直到这个闭包返回true。
- 如果提供了一个
$command:
每次要运行的命令。$onError:
一个可选的回调函数,每次$command
失败时运行。
示例
<?php use function Jralph\Retry\retry; $result = retry(3, function (int $attempt) { // Throwing an error as an example....first 2 attempts will fail. if ($attempt < 2) { throw new Exception('Just throwing an error as an example!'); } return 'Hello World!'; }); // Outputs 'Hello World!' echo $result;
高级用法 / 对象用法
如果您希望对重试工具有更多的灵活性,可以直接使用 Retry
对象,而忽略辅助函数。
Retry
对象完全可链式调用,使操作更简单。
<?php use Jralph\Retry\Retry; use Jralph\Retry\Command; $retry = new Retry(new Command(function (int $attempt) { // Throwing an error as an example....first 2 attempts will fail. if ($attempt < 2) { throw new Exception('Just throwing an error as an example!'); } return 'Hello World!'; })); $result = $retry->attempts(3)->run(); // Outputs 'Hello World!' echo $result;
可用方法
new Retry(Command $command);
运行命令的 Command 对象。$retry->attempts(int $attempts);
尝试执行命令的最大次数。注意,尝试计数为0将永远运行!$retry->wait(int $seconds);
两次尝试之间的秒数。$retry->until(callable $until);
直到$until
的结果返回true时重试。 注意:与$retry->attempts(0);
一起使用效果很好。- 接受
$attempt
作为第一个参数,表示当前尝试次数。 - 接受
$response
作为第二个参数,表示最后一次尝试的响应。
- 接受
$retry->onlyIf(callable $onlyIf);
只有当$onlyIf
返回true时才重试。- 接受
$attempt
作为第一个参数,表示当前尝试次数。 - 接受
$response
作为第二个参数,表示最后一次尝试的响应。
- 接受
$retry->onError(callable $onError);
每次重试失败时运行的回调。- 接受
$attempt
作为第一个参数,表示当前尝试次数。 - 接受
$response
作为第二个参数,表示最后一次尝试的响应。
- 接受
$retry->run();
使用指定的设置运行命令。
变更日志
3.0.0
- 更新到php 8.0+。
2.0.0
- 移除了过时方法。
- 移除了 once, twice, thrice, forever 方法,改用
attempts(int $attempts)
。 - 构造函数仅接受
Command
对象。
1.2.0
- 更新到php 7.1+。
- 弃用
command
方法,改用将命令对象传递给构造函数。
1.1.1
- 将所有使用
\Closure
的方法更改为使用callable
。
- 将所有使用
1.1.0
- 添加了
wait(int $seconds);
方法。
- 添加了