Skip to content

Instantly share code, notes, and snippets.

@useless-stuff
Last active May 20, 2023 23:54
Show Gist options
  • Save useless-stuff/a0bcdbcd4954cbef2d31 to your computer and use it in GitHub Desktop.
Save useless-stuff/a0bcdbcd4954cbef2d31 to your computer and use it in GitHub Desktop.
PHP - Observer pattern with SPL
<?php
abstract class Event
{
public $name, $code;
public function __toString()
{
return $this->name . ' ' . $this->code;
}
public function push(SplSubject $subject)
{
$subject->handle($this);
}
}
class Purchase extends Event
{
const EVENT_NAME = 'PURCHASE';
const EVENT_CODE = 1;
public function __construct()
{
$this->name = self::EVENT_NAME;
$this->code = self::EVENT_CODE;
}
}
class EventsHandler implements SplSubject
{
protected $observers = array();
public $object;
public function attach(SplObserver $observer)
{
$id = spl_object_hash($observer);
$this->observers[$id] = $observer;
}
public function detach(SplObserver $observer)
{
$id = spl_object_hash($observer);
unset($observer[$id]);
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function handle($object)
{
$this->object = $object;
$this->notify();
}
}
class Logger implements SplObserver
{
public function update(SplSubject $subject)
{
error_log("[EVENT] " . (string)$subject->object);
}
}
class EmailSender implements SplObserver
{
public function update(SplSubject $subject)
{
echo 'Email was sent';
}
}
$eventHandler = new EventsHandler();
$eventHandler->attach(new Logger());
$eventHandler->attach(new EmailSender());
$purchase = new Purchase();
$purchase->push($eventHandler);
// Output:
/*
[EVENT] PURCHASE 1
Email was sent
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment