Skip to content

Instantly share code, notes, and snippets.

@bobrik
Created October 23, 2012 19:43
Show Gist options
  • Save bobrik/3941098 to your computer and use it in GitHub Desktop.
Save bobrik/3941098 to your computer and use it in GitHub Desktop.
<?php
// observable user
class User {
const EVENT_TYPE_AFTER_LOAD_FOR_UPDATE = 'afterLoadForUpdate';
const EVENT_TYPE_AFTER_SAVE = 'afterSave';
private $Foo;
// list of observers
private $observers = array();
public function getFoo() {
if (!$this->Foo) {
$this->Foo = new Foo($this);
// register new object as observer
$this->observers[] = $Foo;
}
return $this->Foo;
}
public function loadForUpdate() {
// do real load for update
// fire event for each observer
foreach ($this->observers as $Observer) {
$Observer->handleUserEvent(self::EVENT_TYPE_AFTER_LOAD_FOR_UPDATE, $this);
}
}
public function save() {
// do real save
// fire event for each observer
foreach ($this->observers as $Observer) {
$Observer->handleUserEvent(self::EVENT_TYPE_AFTER_SAVE, $this);
}
}
}
interface UserObserver {
public function handleUserEvent($type, User $User, array $args = array());
}
class Foo implements UserObserver {
private $User;
private $queue = array();
public function __construct(User $User) {
$this->User = $User;
}
public function makeSomeoneHappy() {
echo 'Screw you!'."\n";
// queue some stuff for future
$this->queue[] = 'We all gonna die!';
}
public function handleUserEvent($type, User $User, array $args = array()) {
if ($type == self::EVENT_TYPE_AFTER_SAVE) {
$this->doDeadlyStuff();
}
}
protected function doDeadlyStuff() {
// only say after real User::save
while ($element = array_shift($this->queue)) {
echo $element."\n";
}
}
}
$User = new User();
$Foo = $User->getFoo();
$User->loadForUpdate();
$Foo->makeSomeoneHappy();
// will output: Screw you!
$Foo->makeSomeoneHappy();
// will output: Screw you!
$User->save();
// will output: We all gonna die!
// will output: We all gonna die!
// that's it!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment