Skip to content

async await implementation using generators in php

License

Notifications You must be signed in to change notification settings

logicalsteps/async

Folders and files

NameName
Last commit message
Last commit date
May 7, 2020
May 8, 2020
May 7, 2020
Jun 13, 2018
Oct 3, 2018
May 8, 2019
May 6, 2019
Jun 13, 2018
Oct 31, 2018
Jun 13, 2018
Aug 28, 2020
Jun 13, 2018
Oct 30, 2018

Repository files navigation

Async & Await for PHP

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

Simplify your asynchronous code and make it readable like synchronous code. It works similar to Async and await in other languages such as JavaScript and C#

It can be used standalone with callback functions. It also works with the promise interface of the following frameworks

It can do cooperative multitasking with the event loop interfaces of the following frameworks

Installation

Async can be installed with Composer by adding it as a dependency to your project's composer.json file. It can be done using the following command.

composer require logicalsteps/async

Please refer to Composer's documentation for more detailed installation and usage instructions.

Usage

Consider the following example

<?php
require __DIR__ . '/../vendor/autoload.php';
use Web3\Web3; //installed with `composer require sc0vu/web3.php` on the commandline

function balance($accountNumber)
{
    $web3 = new Web3('http://localhost:8545');
    $eth = $web3->eth;
    $eth->accounts(function ($error, $result) use ($eth, $accountNumber) {
        if ($error) {
            return;
        }
        $accounts = $result;
        $eth->getBalance($accounts[$accountNumber], function ($error, $result) {
            if ($error) {
                return;
            }
            var_export((int)$result->value);
        });
    });
}

balance(0);

If it is all synchronous, our function will simply be

function balance($accountNumber)
{
    $web3 = new Web3('http://localhost:8545');
    $eth = $web3->eth;
    $accounts = $eth->accounts();
    $balance = $eth->getBalance($accounts[$accountNumber]);
    return (int)$balance->value;
}

var_export(balance(0));

With Async library it can be written as the following

use LogicalSteps\Async\Async;
use Web3\Web3;

function balance($accountNumber)
{

    $web3 = new Web3('http://localhost:8545');
    $eth = $web3->eth;
    $accounts = yield [$eth, 'accounts'];
    $balance = yield [$eth, 'getBalance', $accounts[$accountNumber]];
    $value = (int)$balance->value;
    return $value;
}

Async::await(balance(0))->then('var_export');

Now the code is clean and looks synchronous, but runs asynchronously for better performance getting us best of both worlds :)

For more examples and integration with the frameworks take a look at examples folder