ourgold / 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
(在 __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
(在 __invoke
魔法方法中)