guzzle / promises

Promises/A+ library for PHP with synchronous support
MIT License
7.61k stars 116 forks source link

Producer -> consumer chain? #82

Open OnkelTem opened 6 years ago

OnkelTem commented 6 years ago

I don't really understand can I implement producer-consumer scheme using this library?

For example, imagine a producing function which makes some values over time, and another consuming function which takes the values. Is there a way to implement this using Promises?

alexeyshockov commented 6 years ago

The idea of promises is to represent one values per a promise. For generating values over time PHP's generators are more suitable.

$consumerFn = function () {
    while ($value = yield) {
        // Process the value somehow.
        var_dump($value);
    }
};

$consumer = $consumerFn();

// Produce values anywhere in your code.
$consumer->send(1);
$consumer->send(new stdClass());

It's a basic example 1-to-1 producer/subscriber. If you want to implement more complicated schemes, it's better to use events and subscribers, like Symfony's EventDispatcher.