I don't know whether I'll get better answer posting this in 'Php coding' or 'Application design', so I'll just post it in 'PHP coding' since it has more traffic.
Okay, so I've read about observer pattern, seen examples. Seen how to use SPL for the purpose. However, all the examples were basic and only dealt with a single hook. However, I'd like to have multiple hooks within a class and I am confused about whats the best way to achieve that.
I've written a code last night which does this but I'm afraid its very noobish. I'd be grateful to anyone who could point me in the right direction.
Code I wrote last night:
<?php
class Login implements SplSubject {
private $storage;
var $currhook;
function __construct() {
$this->storage = array();
}
function attach( SplObserver $observer ) {
if(!isset($this->storage[$observer->hookName]))
$this->storage[$observer->hookName] = new SplObjectStorage();
$this->storage[$observer->hookName]->attach($observer);
}
function detach( SplObserver $observer) {
$this->storage[$observer->hookName]->detach($observer);
}
function notify() {
foreach ( $this->storage[$this->currhook] as $obs ) {
$obs->update( $this );
}
}
function log_in(){
$this->currhook = 'beforelogin';
$this->notify();
echo "LOGGED IN";
$this->currhook = 'afterlogin';
$this->notify();
}
}
class LoginObserver implements SplObserver {
var $hookName;
function update(SplSubject $login){
$this->doupdate($login);
}
}
class afterLogin extends LoginObserver {
function __construct(Login $login){
$this->hookName = 'beforelogin';
$login->attach($this);
}
function doupdate($login){
echo "beforelogin<br/>";
}
}
class beforeLogin extends LoginObserver {
function __construct(Login $login){
$this->hookName = 'afterlogin';
$login->attach($this);
}
function doupdate($login){
echo "<br/>After login";
}
}
$login = new Login();
new beforeLogin($login);
new afterLogin($login);
$login->log_in();
?>
Pardon the naming inconsistencies.