Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@josuecau
Last active July 11, 2017 04:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josuecau/3848448 to your computer and use it in GitHub Desktop.
Save josuecau/3848448 to your computer and use it in GitHub Desktop.
Observer design pattern implementation in PHP
<?php
class UserList implements SplSubject
{
private $_observers;
private $_users = array();
public function __construct()
{
$this->_observers = new SplObjectStorage();
}
public function addUser($user)
{
$this->_users[] = $user;
$this->notify();
return $this;
}
public function getUsers()
{
return $this->_users;
}
public function getLastUser()
{
$users = $this->getUsers();
return end($users);
}
public function attach(SplObserver $observer)
{
$this->_observers->attach($observer);
return $this;
}
public function detach(SplObserver $observer)
{
$this->_observers->detach($observer);
return $this;
}
public function notify()
{
foreach ($this->_observers as $observer) {
$observer->update($this);
}
return $this;
}
}
class UserListLogger implements SplObserver
{
public function update(SplSubject $subject)
{
printf('User created : "%s"', $subject->getLastUser());
}
}
$ul = new UserList();
$ul->attach(new UserListLogger());
$ul->addUser('Jack');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment