vxm/yii2-async

为 Yii2 应用程序提供一种简单的异步运行代码的方式

安装量: 32,510

依赖者: 0

建议者: 0

安全性: 0

星标: 23

关注者: 2

分支: 6

开放性问题: 1

类型:yii2-extension

1.0.3 2019-06-13 01:58 UTC

This package is auto-updated.

Last update: 2024-09-13 13:30:53 UTC


README

Latest Stable Version Total Downloads Build Status Code Coverage Scrutinizer Code Quality Yii2

关于它

一个扩展,它为基于 spatie/async 的包装器提供了一种简单的方式,以便在 Yii2 应用程序中异步和并行运行代码。

要求

安装

使用 Composer 安装 Yii2 Async

composer require vxm/yii2-async

使用方法

配置

将组件添加到您的应用程序配置文件中

[
    'components' => [
        'async' => [
            'class' => 'vxm\async\Async',
            'appConfigFile' => '@app/config/async.php' // optional when you need to use yii feature in async process.
        ]
    ]
]

由于异步代码在不同的进程中运行,您需要通过属性 appConfigFile 设置 yii 环境,以便通过属性使用组件。异步应用程序配置文件的示例

define('YII_ENV', 'dev');
define('YII_DEBUG', true);

return [
    'id' => 'async-app',
    'basePath' => __DIR__,
    'runtimePath' => __DIR__ . '/runtime',
    'aliases' => [
        '@frontend' => dirname(__DIR__, 2) . '/frontend',
        '@backend' => dirname(__DIR__, 2) . '/backend'
    ]
];

确保在其中定义了所有的别名,以支持自动加载。

运行异步代码

在将其添加到应用程序组件后,现在您可以运行异步代码

Yii::$app->async->run(function() {
     // do a thing.
});

异步事件

在创建异步进程时,您可以在第二个参数中添加以下事件钩子到进程。

Yii::$app->async->run(function() {

    if (rand(1, 2) === 1) {
    
        throw new \YourException;
    }
    
    return 123;
}, [
    'success' => function ($result) {
    
        echo $result; // 123
        
    },
    'catch' => function (\YourException $exception) {
        
        // catch only \YourException
        
    },
    'error' => function() {
    
        // catch all exceptions
        
    },
    'timeout' => function() {
    
        // call when task timeout default's 15s
        
    }
]);

等待进程

有时您需要等待代码执行,只需在 run() 后调用 wait()

Yii::$app->async->run(function() {
    // do a thing.
})->wait();

或者您可以等待多个任务执行

Yii::$app->async->run([YourAsyncClass::class, 'handleA']);
Yii::$app->async->run([YourAsyncClass::class, 'handleD']);
Yii::$app->async->run([YourAsyncClass::class, 'handleC']);
Yii::$app->async->run([YourAsyncClass::class, 'handleD']);

$results = Yii::$app->async->wait(); // results return from tasks above.

与任务一起工作

除了使用闭包之外,您还可以使用 Task。在需要更多子进程设置工作的情况下,Task 非常有用。

Task 类使这变得更容易做到。

use vxm\async\Task;

class MyTask extends Task
{

    public $productId;
    

    public function run()
    {
        // Do the real work here.
       
    }
}

// Do task async use like an anonymous above.

Yii::$app->async->run(new MyTask([
    'productId' => 123

]));