Skip to content

Instantly share code, notes, and snippets.

@sukei
Last active August 24, 2021 11:08
Show Gist options
  • Save sukei/9070924 to your computer and use it in GitHub Desktop.
Save sukei/9070924 to your computer and use it in GitHub Desktop.
An Observer in a Tweet
<?php
/**
* The Signal class is the smallest and fastest observer written in PHP 5.6 and
* using some new features such as the variadic functions and the arguments
* unpacking.
*
* ...and it fits in a tweet.
*
* @author Quentin Schuler aka Sukei <qschuler@neosyne.com>
*/
class Signal {
private $c = [];
function listen($c) { $this->c[] = $c; }
function notify(...$a) { foreach ($this->c as $c) $c(...$a); }
}
@sukei
Copy link
Author

sukei commented Feb 18, 2014

<?php

class Follower
{
    public $name;
    public $onFollow;

    public function __construct($name)
    {
        $this->onFollow = new Signal();
        $this->name = $name;
    }

    public function follow(Follower $follower)
    {
        $follower->onFollow->notify($this);
    }
}
<?php

$neosyne = new Follower('neosyne');
$neosyne->onFollow->listen(function($follower) use ($neosyne) {
    echo sprintf('%s got a new follower: %s.', $neosyne->name, $follower->name);
});

$sukei = new Follower('sukei');
$sukei->follow($neosyne); // neosyne got a new follower: sukei.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment