The observer design pattern enables a subscriber to register with and receive notifications from a provider.
<?php
interface ObserverInterface
{
public function on_change($sender, $arguments);
}
interface ObservableInterface
{
public function add_observer($observer);
}
class Users implements ObservableInterface
{
private $observer;
public function add($name)
{
$this->observer->on_change($this, $name);
}
public function add_observer($observer)
{
$this->observer = $observer;
}
}
class Observer implements ObserverInterface
{
public function on_change($sender, $argument)
{
echo 'User added: ' . $argument . PHP_EOL;
echo 'Sender object: ' . print_r($sender) . PHP_EOL;
}
}
$users = new Users();
$users->add_observer(new Observer());
$users->add('John');
?>