Reactive Programming in PHP

Written by Ben Wendt

Wikipedia has this to say about reactive programming:

In computing, reactive programming is a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will automatically propagate changes through the data flow.

Inspired by projects like knockout.js and reactor.js, I thought I’d give it a shot in PHP. Here is an example implementation:

<?php

$Signal = function($v) {
    if (is_callable($v)) {
        return function() use ($v) {
            return $v();
        };
    } else {
        return function($a = null) use ($v) {
            static $return;
            if (is_null($return)) {
                $return = $v;
            }
            if (!is_null($a)) {
                $return = $a;
            }
            return $return;
        };
    }
};

And here is an example of usage:

<?php

include 'Reactor.php';

$foo = $Signal(1);

$bar = $Signal(function() use ($foo) {
    return $foo() + 1;
});
$bar2 = $Signal(function() use ($foo, $bar) {
    $val = $foo();
    return $val * $val + $bar();
});

echo $foo() . "n";
echo $bar() . "n";
echo $bar2() . "nn";

$foo(2);

echo $foo() . "n";
echo $bar() . "n";
echo $bar2() . "nn";

$foo(0);

echo $foo() . "n";
echo $bar2() . "nn";