libelulasoft/yii2-async-await

关于 PHP yii2 集成中的 Async await,此扩展使用 amphp

安装数: 2,040

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 0

分支: 1

类型:yii2-extension

1.0.0 2022-11-10 00:08 UTC

This package is auto-updated.

Last update: 2024-09-10 05:05:40 UTC


README

PHP yii2 集成的 Async await,此扩展使用 amphp 并支持回调和任务

安装

推荐通过 composer 安装此扩展。

运行以下命令

composer require --prefer-dist libelulasoft/yii2-async-await

或在您的 composer.json 文件的 require 部分添加以下内容

"libelulasoft/yii2-async-await": "~1.0.0"

迁移

如果您想从原版 taguz91/yii2-async-await 迁移到新版本 libelulasoft/yii2-async-await,请按照以下步骤操作

  1. 删除原版
composer remove taguz91/yii2-async-await
  1. 安装新版本
composer require libelulasoft/yii2-async-await
  1. 更新使用此库的 namespace,在整个项目中,我们需要将 taguz91\AsyncAwait\ 替换为 Libelulasoft\AsyncAwait\

  2. 测试以确保一切正常运行。

使用方法

扩展安装后,只需在您的代码中简单使用即可

需要配置 bootstrap 配置 app,因为异步运行在另一个上下文中。

以下示例已在高级模板中进行测试。

例如

return [
    'id' => 'app-async',
    'basePath' => dirname(__DIR__),
    // Your controllers, you can change this to backend\controllers
    'controllerNamespace' => 'frontend\controllers',
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    // Required components for async functions 
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        // Config your database 
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
    ],
    'params' => [],
];

还需要创建入口脚本,以自动加载依赖项并启动 Yii2 应用。

例如

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
// Autoload for composer an yii2 
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';


// Your custom configuration for async 
$config = require __DIR__ . '/async-main.php';
// You can change the console application to web application 
// You dont have acces to vars or configuration in parent context
new yii\console\Application($config);

在 Web 应用中,在 components 部分,您需要添加以下配置

[
    ...,
    'components' => [
        // If you want to use callbacks 
        'asyncAwait' => [
            'class' => \Libelulasoft\AsyncAwait\AsyncAwait::class,
            // Your own entry script, see the above examples
            'loader' => __DIR__ . '/async.php'
        ],
        // If you want to use classes, this is more faster 
        'asyncTask' => [
            'class' => \Libelulasoft\AsyncAwait\AsyncTask::class,
            // Your own entry script, see the above examples
            'loader' => __DIR__ . '/async.php'
        ],
    ]
]

回调使用示例代码

use common\models\User;

// Adding you async function 
Yii::$app->asyncAwait->add('sendUserEmail', function (string $idUser, string $sender) {
    $user = User::findOne($idUser);
    // Return any serializable data, is prefer return a basic array response 
    return \common\models\Email::sendUser($user, $sender);
}, $idUser, $sender);

Yii::$app->asyncAwait->add('sendUserMessage', function (string $message, string $number) {
    if ($number === '') return 'Number is required.';
    return \common\models\Phone::sendMessage($message, $number);
}, $message, $number);

// Execute your asynct functions 
$responses = Yii::$app->asyncAwait->run();
// Getting especific response
$emailResponse = $responses['sendUserEmail'];

任务示例代码

// This class is autoloadable 
namespace common\tasks;

use Amp\Parallel\Worker\Environment;
use Amp\Parallel\Worker\Task;
use yii\helpers\VarDumper;

class PrintTask implements Task
{
    private $text;

    public function __construct(string $text)
    {
        $this->text = $text;
    }

    /**
     * {@inheritdoc}
     */
    public function run(Environment $environment)
    {
        return [
            'response' => "FUTURE PROMISE WORKER {$this->text}",
            'enviroment' => VarDumper::dumpAsString($environment),
        ];
    }
}


/** @var \Libelulasoft\AsyncAwait\AsyncTask */
$async = Yii::$app->asyncTask;

$async->add('1', new PrintTask('THIS IS MY LARGE TEXT'));
$response = $async->run();