Implementing observer pattern in PHP
只是没有如果
只是没有如果 2018-12-10 00:10:46
0
0
1060

// 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 ();


只是没有如果
只是没有如果

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!