Created
July 18, 2015 17:04
-
-
Save anonymous/0309420667a901a4b7ce to your computer and use it in GitHub Desktop.
This file contains 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 SmsNotificationObserver implements SplObserver | |
{ | |
public function update(SplSubject $subject) | |
{ | |
$this->sendSms($subject->getNews()); | |
} | |
private function sendSms($news) | |
{ | |
echo "wysylam sms z nowa wiadomoscia $news<br>"; | |
} | |
} | |
class EmailNotificationObserver implements SplObserver | |
{ | |
public function update(SplSubject $subject) | |
{ | |
$this->sendEmail($subject->getNews()); | |
} | |
private function sendEmail($news) | |
{ | |
echo "wysylam email z nowa wiadomoscia $news<br>"; | |
} | |
} | |
class NewsModelObserver implements SplObserver | |
{ | |
public function update(SplSubject $subject) | |
{ | |
$this->addToDb($subject->getNews()); | |
} | |
private function addToDb($news) | |
{ | |
echo 'dodaje newsy do bazy danych<br>'; | |
} | |
} | |
class NewsDownloader implements SplSubject | |
{ | |
private $observers = array(); | |
public function attach(SplObserver $observer) | |
{ | |
$this->observers[spl_object_hash($observer)] = $observer; | |
} | |
public function detach(SplObserver $observer) | |
{ | |
unset($this->observers[spl_object_hash($observer)]); | |
} | |
public function notify() | |
{ | |
foreach ($this->observers as $observer) { | |
$observer->update($this); | |
} | |
} | |
public function updateNews($news) | |
{ | |
$this->news = $news; | |
$this->notify(); | |
} | |
public function getNews() | |
{ | |
return $this->news; | |
} | |
} | |
$newsDownloader = new NewsDownloader(); | |
$smsNotification = new SmsNotificationObserver(); | |
$emailNotification = new EmailNotificationObserver(); | |
$dbModel = new NewsModelObserver(); | |
$newsDownloader->attach($dbModel); | |
$newsDownloader->attach($emailNotification); | |
$newsDownloader->attach($smsNotification); | |
$newsDownloader->updateNews('Zamknieto baze w USA'); | |
$newsDownloader->updateNews('Polska jest mocarstwem'); | |
$newsDownloader->detach($smsNotification); | |
$newsDownloader->updateNews('Reprezentacja Polski w pilce noznej wygrywa'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment