Home Backend Development PHP Tutorial Simple example of php observer pattern

Simple example of php observer pattern

Jul 25, 2016 am 08:52 AM

  1. //Observed abstract class
  2. class Observed implements SplSubject{
  3. protected $_name;
  4. protected $_observers;
  5. //Instantiation, generate observer object
  6. public function __construct(){
  7. $this-> ;_observers = new SplObjectStorage();
  8. }
  9. //Add observer object
  10. public function attach(SplObserver $observer){
  11. $this->_observers->attach($observer);
  12. }
  13. //Delete observer Object
  14. public function detach(SplObserver $observer){
  15. $this->_observers->detach($observer);
  16. }
  17. //Notification message
  18. public function notify(){
  19. foreach($this-> _observers as $observer){
  20. $observer->showMessage($this);
  21. }
  22. }
  23. //Normal method: Set value
  24. public function setName($name){
  25. $this->_name = $name;
  26. $this->notify();
  27. }
  28. //Normal method: Get value
  29. public function getName(){
  30. return $this->_name;
  31. }
  32. //Normal method: Set age
  33. public function setAge ($age){
  34. $this->age = $age;
  35. foreach($this->_observers as $observer){
  36. $observer->showAge($this->_name,$this-> age);
  37. }
  38. }
  39. }
  40. //Observer abstract class
  41. class Observer implements SplObserver{
  42. //Show message prompt
  43. public function showMessage(SplSubject $obj){
  44. $user = $obj->getName() ;
  45. if($user==='admin'){
  46. echo 'Hello, ',$user,'Welcome to the management background
    ';
  47. }else{
  48. echo "Hello, ' $user' You have been added to the user list
    ";
  49. }
  50. }
  51. //This is an abstract method inherited from the parent class
  52. public function update(SplSubject $subject) {}
  53. //Display personal age
  54. public function showAge($name,$age){
  55. echo "<script>alert('$name's age is: $age')</script>";
  56. }
  57. }
  58. $subject = new Observed( ); //Generate an observed object
  59. $observer = new Observer(); //Generate an observer object
  60. $subject->attach($observer);//Pass the observer into the observed
  61. $subject->setName('Zhang San'); //Call the setName method
  62. /*
  63. * By calling $this->notify();
  64. * By calling $this->notify () will call the $observer->showMessage($this) method,
  65. * that is, the showMessage($obj) method of each observer object;
  66. */
  67. $subject->setName('admin');
  68. $subject->setAge(24);
Copy code

Example 2, observer mode:

  1. interface Subject
  2. {
  3. public function Attach($Observer); //Add an observer
  4. public function Detach($Observer); //Kick out the observer
  5. public function Notify(); //Meet the conditions Notify observers when
  6. public function SubjectState($Subject); //Observation conditions
  7. }
  8. class Boss Implements Subject
  9. {
  10. public $_action;
  11. private $_Observer;
  12. public function Attach($Observer)
  13. {
  14. $this- >_Observer[] = $Observer;
  15. }
  16. public function Detach($Observer)
  17. {
  18. $ObserverKey = array_search($Observer, $this->_Observer);
  19. if($ObserverKey !== false)
  20. {
  21. unset($this->_Observer[$ObserverKey]);
  22. }
  23. }
  24. public function Notify()
  25. {
  26. foreach($this->_Observer as $value)
  27. {
  28. $value->Update( );
  29. }
  30. }
  31. public function SubjectState($Subject)
  32. {
  33. $this->_action = $Subject;
  34. }
  35. }
  36. abstract class Observer
  37. {
  38. protected $_UserName;
  39. protected $_Sub; __construct($Name,$Sub)
  40. {
  41. $this->_UserName = $Name;
  42. $this->_Sub = $Sub;
  43. }
  44. public abstract function Update(); //Receive the method
  45. } / /bbs.it-home.org
  46. class StockObserver extends Observer
  47. {
  48. public function __construct($name,$sub)
  49. {
  50. parent::__construct($name,$sub);
  51. }
  52. public function Update()
  53. {
  54. echo $this->_Sub->_action.$this->_UserName." Run quickly...";
  55. }
  56. }
  57. $huhansan = new Boss(); //Observed person
  58. $ gongshil = new StockObserver("三毛",$huhansan); //Initialize the observer
  59. $huhansan->Attach($gongshil); //Add an observer
  60. $huhansan->Attach($gongshil); / /Add an identical observer
  61. $huhansan->Detach($gongshil); //Kick out an observer in the base
  62. $huhansan->SubjectState("The police are coming"); //Meet the conditions that are met
  63. $huhansan->Notify(); //Copy code
through all valid observers

Instructions: A class (let's call it an Observable) that inherits the interface of an Observable container The methods in this interface include: add observer, kick out observer, remind observer, and observation conditions Adding an observer is equivalent to registering some classes into this container. Of course, the premise of these classes is that they need to have a method that responds to the observed information. The observed container accepts different observation condition parameters to determine whether it needs to remind all registered observers in the container to respond accordingly. Once the reminder conditions are met, all observers in the container are reminded to call the corresponding methods and implement changes to the corresponding observer instances.



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles