Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created June 3, 2013 17:26
Show Gist options
  • Save ackintosh/5699747 to your computer and use it in GitHub Desktop.
Save ackintosh/5699747 to your computer and use it in GitHub Desktop.
Observer pattern in PHP with SplObjectStrage.
<?php
class Subject
{
private $observers;
public $message;
public function __construct()
{
$this->observers = new SplObjectStorage();
}
public function add_observer(Observer $observer)
{
$this->observers->attach($observer);
}
public function update($message)
{
$this->message = $message;
foreach ($this->observers as $o) {
$o->update($this);
}
}
}
class Observer
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function update(Subject $subject)
{
echo "{$this->name} was received message. '{$subject->message}'".PHP_EOL;
}
}
$o1 = new Observer('observer 1');
$o2 = new Observer('observer 2');
$s = new Subject();
$s->add_observer($o1);
$s->add_observer($o2);
$s->update('shut the fuck up and write some code.');
// observer 1 was received message. 'shut the fuck up and write some code.'
// observer 2 was received message. 'shut the fuck up and write some code.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment