observer_001.phpt 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. --TEST--
  2. SPL: SplObserver and SplSubject (empty notify)
  3. --FILE--
  4. <?php
  5. class ObserverImpl implements SplObserver
  6. {
  7. protected $name = '';
  8. function __construct($name = 'obj')
  9. {
  10. $this->name = '$' . $name;
  11. }
  12. function update(SplSubject $subject): void
  13. {
  14. echo $this->name . '->' . __METHOD__ . '(' . $subject->getName() . ");\n";
  15. }
  16. function getName()
  17. {
  18. return $this->name;
  19. }
  20. }
  21. class SubjectImpl implements SplSubject
  22. {
  23. protected $name = '';
  24. protected $observers = array();
  25. function __construct($name = 'sub')
  26. {
  27. $this->name = '$' . $name;
  28. }
  29. function attach(SplObserver $observer): void
  30. {
  31. echo '$sub->' . __METHOD__ . '(' . $observer->getName() . ");\n";
  32. if (!in_array($observer, $this->observers))
  33. {
  34. $this->observers[] = $observer;
  35. }
  36. }
  37. function detach(SplObserver $observer): void
  38. {
  39. echo '$sub->' . __METHOD__ . '(' . $observer->getName() . ");\n";
  40. $idx = array_search($observer, $this->observers);
  41. if ($idx !== false)
  42. {
  43. unset($this->observers[$idx]);
  44. }
  45. }
  46. function notify(): void
  47. {
  48. echo '$sub->' . __METHOD__ . "();\n";
  49. foreach($this->observers as $observer)
  50. {
  51. $observer->update($this);
  52. }
  53. }
  54. function getName()
  55. {
  56. return $this->name;
  57. }
  58. }
  59. $sub = new SubjectImpl;
  60. $ob1 = new ObserverImpl("ob1");
  61. $ob2 = new ObserverImpl("ob2");
  62. $ob3 = new ObserverImpl("ob3");
  63. $sub->attach($ob1);
  64. $sub->attach($ob1);
  65. $sub->attach($ob2);
  66. $sub->attach($ob3);
  67. $sub->notify();
  68. $sub->detach($ob3);
  69. $sub->notify();
  70. $sub->detach($ob2);
  71. $sub->detach($ob1);
  72. $sub->notify();
  73. $sub->attach($ob3);
  74. $sub->notify();
  75. ?>
  76. --EXPECT--
  77. $sub->SubjectImpl::attach($ob1);
  78. $sub->SubjectImpl::attach($ob1);
  79. $sub->SubjectImpl::attach($ob2);
  80. $sub->SubjectImpl::attach($ob3);
  81. $sub->SubjectImpl::notify();
  82. $ob1->ObserverImpl::update($sub);
  83. $ob2->ObserverImpl::update($sub);
  84. $ob3->ObserverImpl::update($sub);
  85. $sub->SubjectImpl::detach($ob3);
  86. $sub->SubjectImpl::notify();
  87. $ob1->ObserverImpl::update($sub);
  88. $ob2->ObserverImpl::update($sub);
  89. $sub->SubjectImpl::detach($ob2);
  90. $sub->SubjectImpl::detach($ob1);
  91. $sub->SubjectImpl::notify();
  92. $sub->SubjectImpl::attach($ob3);
  93. $sub->SubjectImpl::notify();
  94. $ob3->ObserverImpl::update($sub);