Observer.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * 观察者
  4. * @author Jinhui Zhu
  5. *
  6. * 用法:
  7. * class User
  8. * {
  9. * public $observer;
  10. * public function __construct()
  11. * {
  12. * $this->observer = new \Qii_Driver_Observer($this);
  13. * }
  14. * public function signup($email, $password)
  15. * {
  16. * //todo
  17. * //执行notify通知观察者
  18. * $this->observer->notify($email, $password);
  19. * }
  20. * }
  21. * class emailObserver implements \SplObserver
  22. * {
  23. * public function update(SplSubject $subject)
  24. * {
  25. * //todo
  26. * $email = func_get_arg(1);
  27. * $password = func_get_arg(2);
  28. * echo '发送邮件到'. $email . ', 你的密码是'. $password . '请妥善保管';
  29. * }
  30. * }
  31. * $user = new User();
  32. * $user->observer->attach($emailObserver);
  33. * $user->signup('email@test.com', '123456');
  34. */
  35. namespace Qii\Driver;
  36. use SplSubject;
  37. use SplObjectStorage;
  38. use SplObserver;
  39. class Observer implements SplSubject
  40. {
  41. private $observers = NULL;
  42. //上下文
  43. public $context;
  44. /**
  45. * Observer constructor.
  46. * @param $context 调用此方法的类
  47. */
  48. public function __construct($context)
  49. {
  50. if (!isset($context) || !$context || !is_object($context)) throw new \Exception(\Qii::i(1003), __LINE__);
  51. $this->context = $context;
  52. $this->observers = new \SplObjectStorage();
  53. }
  54. /**
  55. * 添加观察者
  56. * @param SplObserver $observer
  57. */
  58. public function attach(\SplObserver $observer)
  59. {
  60. $this->observers->attach($observer);
  61. }
  62. /**
  63. * 移除观察者
  64. * @param SplObserver $observer
  65. */
  66. public function detach(\SplObserver $observer)
  67. {
  68. $this->observers->detach($observer);
  69. }
  70. /**
  71. * 发送通知 调用此方法需要传递一个参数
  72. */
  73. public function notify()
  74. {
  75. $result = array();
  76. $args = func_get_args();
  77. array_unshift($args, $this);
  78. foreach ($this->observers as $observer) {
  79. $result[] = call_user_func_array(array($observer, 'update'), $args);
  80. }
  81. return $result;
  82. }
  83. }