ruth / async-service-call-bundle
Symfony 异步服务方法调用包
1.1.4
2020-04-12 13:47 UTC
Requires
- php: >=7.3
- symfony/console: ~5.0
- symfony/framework-bundle: ~5.0
- symfony/monolog-bundle: ^3.5
- symfony/process: ^5.0
Requires (Dev)
- symfony/phpunit-bridge: >=5.0
README
此包允许您在后台进程中异步执行服务的方法。
它是基于 krlove/async-service-call-bundle 的分支,更新以在 Symfony 4 或 5 中运行。
安装
使用 composer 安装
composer require ruth/async-service-call-bundle
它应该会在 config/bundles.php
中启用该包
return [
...
new Krlove\AsyncServiceCallBundle\KrloveAsyncServiceCallBundle(),
]
如果没有,你现在知道该怎么做。
配置
选项
console_path
- 到console
脚本的路径。可以是绝对路径或相对于kernel.project_dir
参数值的相对路径。默认为bin/console
Symfony 4.* 和 Symfony 5.*。php_path
- 到 php 可执行文件的路径。如果没有在配置中提供选项,将使用Symfony\Component\Process\PhpExecutableFinder::find
来设置它。
示例
# config/packages/krlove_async_service_call.yaml
krlove_async_service_call:
console_path: bin/console
php_path: /usr/local/bin/php
用法
定义任何服务
<?php
namespace App\Service;
class AwesomeService
{
public function doSomething($int, $string, $array)
{
// do something heavy
sleep(10);
}
}
注册服务
# services.yml
services:
app.service.awesome:
class: App\Service\AwesomeService
public: true
确保你的服务配置了
public: true
异步执行 doSomething
方法
$this->get('krlove.async')
->call('app.service.awesome', 'doSomething', [1, 'string', ['array']);
上面的行将通过在后台运行 krlove:service:call
命令来执行 App\Service\AwesomeService::doSomething
方法。
你可以在控制台中通过调用 top
来跟踪其执行。
原始方法使用 symfony process 的 Symfony\Component\Process\Process
已被废弃,转而使用更传统的 exec
php 函数。原因如下(你可以在上一页找到)
If a Response is sent before a child process had a chance to complete, the server process will be killed (depending on your OS).
It means that your task will be stopped right away.
Running an asynchronous process is not the same as running a process that survives its parent process.
使用 Symfony Process 组件的用法
还可以使用 Symfony Process 组件运行你的服务,并在此过程中异步服务具有响应(或异常)。
为此,只需像这样调用方法 getProcessInstance
// 1. Standard way:
$process = $this->get('krlove.async')
->getProcessInstance('app.service.awesome', 'doSomething', [1, 'string', ['array']);
// and to run asynchronously
$process->start();
// ... do other things
$process->wait();
// ... do things after the process has finished
$result = $process->getOutput();
// 2. With callback function after service finishes:
$process = $this->get('krlove.async')
->getProcessInstance('app.service.awesome', 'doSomething', [1, 'string', ['array']);
// and to run asynchronously
$result = null;
$process->start(function ($res) use($process, &$result) {
$result = $process->getOutput();
});
// ... do other things
$process->wait();
// you now have result from async service call available at $result variable.
有关 Symfony Process 组件的更多信息,请参阅 这里