ourgoldpackages / exchange
与外部服务通信的工具
Requires
- php: ^7.2|^8.0
- ext-json: *
- laravel/framework: ^5.5 || ^6 || ^7 || ^10
README
安装
composer require ourgold/exchange:^1.0
注意:(如果需要,可以谨慎添加 --ignore-platform-reqs
参数)
安装完成后,执行以下命令
php artisan vendor:publish --provider="Ourgold\Exchange\ExchangeServiceProvider" --tag="config"
并且 必须 编辑 api_superclass
参数,指定所需的超类代替默认的。
配置完成后,执行迁移
php artisan migrate
并将命令添加到 app/Console/Kernel.php
中的 schedule
方法
$schedule->command('exchange:process-queue')->everyMinute();
使用
要使用,需要实现自己的 \Ourgold\Exchange\Services\ExternalAPIs
类版本,在其中添加返回用于处理外部API的类实例的方法。
之后,为了将请求放入队列,需要调用 \Ourgold\Exchange\Services\ExchangeService::queue()
方法
第一个参数 - 一个包含依次调用(每个后续调用基于前一个调用的结果)的方法名称的数组 第二个参数 - 一个数组,包含传递给链中最后一个方法的参数 第三个参数 - 一个实现了 __invoke
方法的 callback 类,其中将传递最后一个方法的调用结果
示例 1
\Ourgold\Exchange\Services\ExchangeService::queue(
[
'exampleAPI',
'users',
'get',
],
null,
\App\TestCallbackHandler::class,
);
调用链
(new \Ourgold\Exchange\Services\ExternalAPIsTest())->exampleAPI()->users()->get();
在此示例中,首先将在 \Ourgold\Exchange\Services\ExternalAPIs
类中调用 exampleAPI()
方法,该方法返回 ExternalAPIExample
类的实例。
然后将在 ExternalAPIExample
类中调用 users()
方法,最后调用 get()
方法。没有参数传递(第二个参数)。调用结果将传递给 callback 类 \App\TestCallbackHandler
(在 magic 方法 __invoke
中)
示例 2
\Ourgold\Exchange\Services\ExchangeService::queue(
[
'exampleAPI',
'login',
],
['test_login', 'test_password'],
\App\TestCallbackHandler::class,
);
调用链
(new \Ourgold\Exchange\Services\ExternalAPIsTest())->exampleAPI()->login('test_login', 'test_password');
在此示例中,首先将在 \Ourgold\Exchange\Services\ExternalAPIs
类中调用 exampleAPI()
方法,该方法返回 ExternalAPIExample
类的实例。
然后调用 login($login, $password)
方法,该方法接受参数 test_login
和 test_password
。调用结果将传递给 callback 类 \App\TestCallbackHandler
(在 magic 方法 __invoke
中)