Created
February 18, 2019 03:43
-
-
Save phptuts/be764a6e08320a9acb799d066a563011 to your computer and use it in GitHub Desktop.
Observer Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface Subject { | |
public function attach(Observable $observable); | |
public function detach(Observable $observable); | |
public function next($value); | |
} | |
interface Observable { | |
public function __construct($eventName); | |
public function subscribe($value); | |
public function eventName(); | |
} | |
class Notify implements Subject { | |
/** | |
* @var Observable[] | |
*/ | |
protected $observables; | |
public function attach(Observable $observable) | |
{ | |
$this->observables[$observable->eventName()] = $observable; | |
} | |
public function detach(Observable $observable) | |
{ | |
unset($this->observables[$observable->eventName()]); | |
} | |
public function next($value) | |
{ | |
foreach ($this->observables as $observable) { | |
$observable->subscribe($value); | |
} | |
} | |
} | |
class Email implements Observable { | |
private $eventName; | |
public function __construct($eventName) | |
{ | |
$this->eventName = $eventName; | |
} | |
public function subscribe($value) | |
{ | |
var_dump('SEND EMAIL ' . $value); | |
} | |
public function eventName() | |
{ | |
return $this->eventName; | |
} | |
} | |
class Pager implements Observable { | |
private $eventName; | |
public function __construct($eventName) | |
{ | |
$this->eventName = $eventName; | |
} | |
public function subscribe($value) | |
{ | |
var_dump('PAGE USER ' . $value); | |
} | |
public function eventName() | |
{ | |
return $this->eventName; | |
} | |
} | |
$notify = new Notify(); | |
$notify->attach(new Email('send_email_to_admin')); | |
$notify->attach(new Pager('send_page_duty')); | |
$notify->attach(new Email('send_email_to_cto')); | |
$notify->next('server down'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment