Skip to content

Instantly share code, notes, and snippets.

@sangheonhan
Created January 11, 2019 07:09
Show Gist options
  • Save sangheonhan/aa3e59dadcde6d8abdc5e845c8585b05 to your computer and use it in GitHub Desktop.
Save sangheonhan/aa3e59dadcde6d8abdc5e845c8585b05 to your computer and use it in GitHub Desktop.
SplObjserver 예제
<?php
class Channel implements Splsubject
{
private $members;
private $name;
private $teller;
private $message;
public function __construct($name)
{
$this->name = $name;
$this->members = array();
}
public function attach(SplObserver $player)
{
$this->members[] = $player;
}
public function detach(SplObserver $player)
{
$key = array_search($player, $this->members, true);
if ($key) {
unset($this->members[$key]);
}
}
public function notify()
{
foreach ($this->members as $player) {
$player->update($this);
}
}
public function shout($teller, $message)
{
$this->teller = $teller;
$this->message = $message;
$this->notify();
}
public function teller()
{
return $this->teller;
}
public function message()
{
return $this->message;
}
}
class Player implements Splobserver
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function name()
{
return $this->name;
}
public function update(SplSubject $subject)
{
echo "{$this->name} listen to {$subject->teller()->name()}: {$subject->message()}\n";
}
}
$channel = new Channel('Public');
$repin = new Player('Repin');
$invis = new Player('Invis');
$runestaler = new Player('Runestalker');
$channel->attach($repin);
$channel->attach($invis);
$channel->attach($runestaler);
$channel->shout($repin, 'Rok\'tar!');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment