• Stars
    star
    105
  • Rank 328,196 (Top 7 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 5 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⏳ Futures, Streams & Async/Await for PHP's Swoole asynchronous run-time.

Swoole Futures

https://github.com/leocavalcante/swoole-futures/actions?query=workflow%3ACI https://shepherd.dev/github/leocavalcante/swoole-futures

Futures, Streams & Async/Await for PHP's Swoole asynchronous run-time.

Inspired by futures Crate for Rust's Tokio asynchronous run-time.

It's on top of Swoole's coroutines system there is no special wizardry, just sugar.

Install

composer require leocavalcante/swoole-futures

Usage

Async / await

Creates and awaits for asynchronous computations in an alternative style than Swoole's coroutines.

$future = Futures\async(fn() => 1);
$result = $future->await(); // 1

Futures are lazy, it only runs when you call await.

Join

Joins a list of Futures into a single Future that awaits for a list of results.

$slow_rand = function (): int {
    Co::sleep(3);
    return rand(1, 100);
};

$n1 = Futures\async($slow_rand);
$n2 = Futures\async($slow_rand);
$n3 = Futures\async($slow_rand);

$n = Futures\join([$n1, $n2, $n3]);

print_r($n->await());

This takes 3 seconds, not 9, Futures runs concurrently! (Order isn't guaranteed)

Race

Returns the result of the first finished Future.

use Swoole\Coroutine\Http\Client;

$site1 = Futures\async(function() {
    $client = new Client('www.google.com', 443, true);
    $client->get('/');
    return $client->body;
});

$site2 = Futures\async(function() {
    $client = new Client('www.swoole.co.uk', 443, true);
    $client->get('/');
    return $client->body;
});

$site3 = Futures\async(function() {
    $client = new Client('leocavalcante.dev', 443, true);
    $client->get('/');
    return $client->body;
});

$first_to_load = Futures\race([$site1, $site2, $site3]);

echo $first_to_load;

And there is a Futures\select alias.

Async map

Maps an array into a list of Futures where which item runs concurrently.

$list = [1, 2, 3];
$multiply = fn(int $a) => fn(int $b) => $a * $b;
$double = $multiply(2);

$doubles = Futures\join(Futures\async_map($list, $double))->await();

print_r($doubles);

Then

Sequences a series of steps for a Future, is the serial analog for join:

use function Futures\async;

$future = async(fn() => 2)
    ->then(fn(int $i) => async(fn() => $i + 3))
    ->then(fn(int $i) => async(fn() => $i * 4))
    ->then(fn(int $i) => async(fn() => $i - 5));

echo $future->await(); // 15

Stream

Streams values/events from sink to listen with between operations.

$stream = Futures\stream()
    ->map(fn($val) => $val + 1)
    ->filter(fn($val) => $val % 2 === 0)
    ->map(fn($val) => $val * 2)
    ->listen(fn($val) => print("$val\n")); // 4 8 12 16 20

foreach (range(0, 9) as $n) {
    $stream->sink($n);
}

MIT © 2020

More Repositories

1

siler

⚡ Flat-files and plain-old PHP functions rockin'on as a set of general purpose high-level abstractions.
PHP
1,127
star
2

encrypt

🔒 A set of high-level APIs over PointyCastle for two-way cryptography.
Dart
323
star
3

page_view_indicator

👆🏻 Builds indication marks for PageView.
Dart
160
star
4

Docktober

🍂 Simple: Docker + OctoberCMS
56
star
5

hyperf-doctrine

🎲 This project provides an integration for the Doctrine ORM and the Hyperf framework.
PHP
52
star
6

password-dart

A set of high-level APIs over PointyCastle and CryptoUtils to hash and verify passwords securely.
Dart
49
star
7

ReduRx

👌 A thin layer of a Redux-based state manager on top of RxDart
Dart
41
star
8

observable_state

🔭 Flutter's State Manager for Reactive Apps in a Centralized and Predictable container.
Dart
39
star
9

aws-lambda-swoole-runtime

λ Run PHP Coroutines & Fibers as-a-Service on the AWS Lambda.
PHP
38
star
10

awesome-payments-br

Awesome list of payment gateways in Brazil
38
star
11

dwoole

⚙️ Docker image for Swoole apps with Composer, auto-restart on development and a production-ready version.
PHP
32
star
12

my-awesome-frontend

🎈 Just one link per motivation
30
star
13

up-n-running-k8s

💠 Step-by-step guide of a custom and universal setup for plain VPSs or bare-metal servers using free and open tools.
30
star
14

ippo

Immutable, Statically-typed, Cloneable and Serializable Auto-generated Plain-old PHP Objects
PHP
29
star
15

Flutter-ReduRx

🎯 Flutter bindings for ReduRx.
Dart
25
star
16

meteor-redux

Meteorux? Reduxor? Let's find out!
JavaScript
24
star
17

request-callback

➰ Swoole request callback for PSR compliant handlers.
PHP
24
star
18

redact-sensitive

🙈 A Monolog processor that protects sensitive data from miss logging
PHP
22
star
19

swoole-postgresql-doctrine-driver

🔌 A Doctrine DBAL Driver implementation on top of Swoole Coroutine PostgreSQL client
PHP
22
star
20

kafka-phplayground

🎸 Just some fun with Kafka, PHP and Swoole
PHP
20
star
21

inmana-php

🚀 Developing Rocketseat's Next Level Week (NLW#05) Application using PHP/Swoole + Hyperf
PHP
20
star
22

create-siler-app

🧱 Set up a modern Siler app by running one command.
PHP
16
star
23

intel-codenames-picker

🤔 Pick a random Intel codename for you next project!
JavaScript
16
star
24

oc-websockets

Add real-time features to your OctoberCMS project.
PHP
15
star
25

shape

Run-time type checks against plain old PHP arrays
PHP
14
star
26

rustancean-radar

🦀 A fearless approach to Rocketseat's OminiStack week.
Rust
14
star
27

swoole-irc-client

💬 Swoole based IRC (Internet Relay Chat) Client
PHP
14
star
28

Fusic

🎵 Music with F#: The Language and the Note
F#
13
star
29

rphc

PHP-to-PHP RPC Framework
PHP
12
star
30

nginxless

PoC of Swoole serving PHP-FPM requests for popular frameworks like Laravel & WordPress.
PHP
9
star
31

The-Minimal-React

Before create-react-app was cool
JavaScript
9
star
32

be-the-hero

OminiStack week v11.0... but in Rust! 🦀
Rust
8
star
33

php-go-scylladb

👻 Proof of concept on making CQL queries to ScyllaDB from PHP using Spiral's Goridge and Go's shard-aware driver.
PHP
8
star
34

publican

🧔 The package that will help you out with Dart's Pub 🎯
Dart
8
star
35

php-algebraic-effects

🥓 PoC of Algebraic Effects in PHP programming language
PHP
7
star
36

nanoroku

⚛️ Hyperf's Nano + Salesforce's Heroku
PHP
7
star
37

swoole-mutex

🚦 Mutual exclusion abstractions for PHP's Swoole concurrency run-time.
PHP
7
star
38

closure-chain

⛓️ Chain of responsibility pattern for your Closures
PHP
7
star
39

result

🎁 Result provides an alternative error handling mechanism, avoiding throwing exceptions or using nulls.
PHP
7
star
40

swoole-graphql-api

Building a GraphQL API on top of Swoole.
PHP
7
star
41

newrelic-telemetry-sdk-php

Unofficial PHP library for sending telemetry data to New Relic.
PHP
7
star
42

rust-snake

🐍 Learning Rust doing a Snake game with the help of SDL2.
Rust
6
star
43

oc-minimal-react

Get started with React on OctoberCMS.
JavaScript
6
star
44

tracing-nano

🔭 Proof of concept on adding observability features (tracing and metrics) to a Nano microservice (using existing Hyperf components).
PHP
5
star
45

vlog

✌️ Building a 150 KB web blog in V & SQLite
V
5
star
46

viewi-swoole

🚀 Serving a Viewi application with a Swoole server.
PHP
5
star
47

oc-backendusertree

Adds SimpleTree trait functionality to OctoberCMS's backend users.
PHP
5
star
48

cheer-your-title

Sometimes your <title> tag needs some joy
JavaScript
4
star
49

fsharp-mongodb-api

REST API with MongoDB and F# on .NET Core.
F#
4
star
50

crisgon

Kind-of compiler fun to generate CSS pixel images
JavaScript
3
star
51

swoole-mysql-lock

🔒 Experimenting MySQL locks for concurrent Swoole processes.
PHP
3
star
52

phull

Client-server communication between JS and PHP via Ajax long polling.
PHP
3
star
53

mars

Meteor, Apollo, Redux & React
JavaScript
3
star
54

simplest-php-website-ever

Simplest PHP website ever!
PHP
3
star
55

coroutine-context-api

Using Coroutines Contexts as Hierarchal Service Locators and Dependency Injection Containers
PHP
3
star
56

loadtest

HTTP server snippets to load test.
Batchfile
3
star
57

dotfiles

My personal dotfiles
Emacs Lisp
2
star
58

free-deploy

💸 Full-stack React (Next.js) & MongoDB application exploring generous free plans from Vercel and Atlas.
TypeScript
2
star
59

dispatch

🕊️ Event dispatcher awareness made simple.
PHP
2
star
60

merw6n

MEAN? MERW6N! WTF?
JavaScript
2
star
61

otel-php-metrics

Very small example application to debug HTTP requests no summing up.
PHP
2
star
62

yet-another-clean-architecture-example

📐 YACAE shows off a proof of concept for a Clean Architecture trying to follow some basic principles
PHP
2
star
63

exercism-rust

🏋️ My solutions for Exercism's Rust track
Rust
1
star
64

nano-goridge

Proof of concept on running Hyperf's Nano with Spiral's Goridge
PHP
1
star
65

rusty-rocket

Working out on Rust and Rocket web framework
Rust
1
star
66

dartlangbr

Exemplo de como criar e publicar pacotes de bibliotecas Dart no Pub.
Dart
1
star
67

swoole-examples

📓 Learning and teaching Swoole by examples
PHP
1
star
68

php-dev

🐘 Docker based development environment for PHP source-code.
Dockerfile
1
star
69

go-intensivo

Working on Go Intensivo class
Go
1
star
70

phpaskell

Trying to implement Category Theory concepts in PHP to help understanding Haskell
PHP
1
star
71

write

Notes, ideas, articles, screenwriting, papers, drafts, thoughts... Just write!
1
star
72

phusic

PHP port of the Fusic experiment
PHP
1
star
73

risp

🦀📜 (rust-based (cli-tool (to-work-with (lists))))
Rust
1
star
74

hello-dapr

🎩 Running PHP's Dapr SDK within Swoole & Hyperf.
PHP
1
star
75

leocavalcante.org

*.org
Makefile
1
star
76

slimr

Wire up dependencies, routes and hooks in your Slim application and use Controllers as Services.
PHP
1
star
77

tracking-analytics

Track any kind of action in a Google Analytics account even out of a page you control (i.e. Pixel Tracking)
PHP
1
star
78

nedo

󠀼Nedo.html is a HTML runtime built as a PoC for people who think markup languages can't be programming languages.
Rust
1
star