Created
January 11, 2019 07:09
-
-
Save sangheonhan/aa3e59dadcde6d8abdc5e845c8585b05 to your computer and use it in GitHub Desktop.
SplObjserver 예제
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 | |
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