Home  >  Q&A  >  body text

Implementing observer pattern in PHP

// Implementation function: Notify security module and advertising module when logging in

// Predefined interface: SplObserver observer and SplSubject observer

class User implements SplSubject

{

protected $login_num;

protected $hobby;

protected $_subject;

public function __construct($login_num, $hobby)

{

$this->login_num = $login_num;

$this->hobby = $hobby;

//Storage observer object

$this->_subject = new SplObjectStorage();

}

public function __get($name)

{

// TODO: Implement __get() method.

return $this->$name;

}

public function login()

{

// Operation...

$this->notify();

}

// SplSubject interface

public function attach(SplObserver $observer)

{

// TODO: Implement attach() method.

$this->_subject->attach($ observer);

}

public function detach(SplObserver $observer)

{

// TODO: Implement detach() method.

$this->_subject->detach($observer);

}

public function notify()

{

/ / TODO: Implement notify() method.

foreach ($this->_subject as $observer) {

$observer->update($this);

}

}

}

// The observer observes user login here

// Security check

class safe implements SplObserver

{

public function update(SplSubject $subject)

{

// TODO: Implement update() method.

if ($subject->login_num > 10) {

echo 'You have logged in more than 10 times today. There may be a password leak problem. Please reset your password! ';

} else {

echo 'Today's' . $subject->login_num . 'Safe login! ';

}

}

}

// Advertising promotion

class ad implements SplObserver

{

public function update(SplSubject $subject)

{

// TODO: Implement update() method.

if ($subject-> hobby == 'sports') {

echo 'This is a sports advertisement! ';

} else {

echo 'Random ad! ';

}

}

}

$hobby = ['sports', 'eat', 'drink', 'sleep', ' play'];

$user = new User(random_int(1, 20), $hobby[shuffle($hobby)]);

$user->attach(new safe( ));

$user->attach(new ad());

// A series of observers are triggered when the user logs in

$user->login ();


只是没有如果只是没有如果2161 days ago1061

reply all(0)I'll reply

No reply
  • Cancelreply