Skip to content

Instantly share code, notes, and snippets.

Created July 18, 2015 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/0309420667a901a4b7ce to your computer and use it in GitHub Desktop.
Save anonymous/0309420667a901a4b7ce to your computer and use it in GitHub Desktop.
<?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