SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/Event_Subject.php

Copyright (C) 2017 Karmabunny Pty Ltd.

This file is a part of SproutCMS.

SproutCMS is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation, either
version 2 of the License, or (at your option) any later version.

For more information, visit <http://getsproutcms.com>.

This class was originally from Kohana 2.3.4
Copyright 2007-2008 Kohana Team
  1. <?php
  2. /**
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  *
  13.  * This class was originally from Kohana 2.3.4
  14.  * Copyright 2007-2008 Kohana Team
  15.  */
  16. namespace Sprout\Helpers;
  17.  
  18. use Kohana_Exception;
  19.  
  20.  
  21. /**
  22.  * Kohana event subject. Uses the SPL observer pattern.
  23.  */
  24. abstract class Event_Subject {
  25.  
  26. // Attached subject listeners
  27. protected $listeners = array();
  28.  
  29. /**
  30.   * Attach an observer to the object.
  31.   *
  32.   * @chainable
  33.   * @param object Event_Observer
  34.   * @return object
  35.   */
  36. public function attach(Event_Observer $obj)
  37. {
  38. if ( ! ($obj instanceof Event_Observer))
  39. throw new Kohana_Exception('eventable.invalid_observer', get_class($obj), get_class($this));
  40.  
  41. // Add a new listener
  42. $this->listeners[spl_object_hash($obj)] = $obj;
  43.  
  44. return $this;
  45. }
  46.  
  47. /**
  48.   * Detach an observer from the object.
  49.   *
  50.   * @chainable
  51.   * @param object Event_Observer
  52.   * @return object
  53.   */
  54. public function detach(Event_Observer $obj)
  55. {
  56. // Remove the listener
  57. unset($this->listeners[spl_object_hash($obj)]);
  58.  
  59. return $this;
  60. }
  61.  
  62. /**
  63.   * Notify all attached observers of a new message.
  64.   *
  65.   * @chainable
  66.   * @param mixed message string, object, or array
  67.   * @return object
  68.   */
  69. public function notify($message)
  70. {
  71. foreach ($this->listeners as $obj)
  72. {
  73. $obj->notify($message);
  74. }
  75.  
  76. return $this;
  77. }
  78.  
  79. } // End Event Subject
  80.