ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
Subject.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
28{
32 protected array $observer_groups = [];
33
34 public function __construct()
35 {
36 $this->initObserverGroup((Event::ALL)->value);
37 }
38
39 public function attach(Observer $observer, Event $event): void
40 {
41 $this->initObserverGroup($event->value);
42
43 $this->observer_groups[$event->value][] = $observer;
44 }
45
46 public function detach(Observer $observer, Event $event = Event::ALL): void
47 {
48 $this->initObserverGroup($event->value);
49
50 foreach ($this->observer_groups[$event->value] as $index => $attached_observer) {
51 if ($attached_observer->getId() === $observer->getId()) {
52 unset($this->observer_groups[$event->value][$index]);
53 }
54 }
55 }
56
57 public function notify(Event $event, ?Data $data): void
58 {
59 $this->initObserverGroup($event->value);
61 $observers = array_merge(
62 $this->observer_groups[(Event::ALL)->value],
63 $this->observer_groups[$event->value],
64 );
65
66 foreach ($observers as $interested_observer) {
67 try {
68 $interested_observer->update($event, $data);
69 } catch (Throwable $e) {
70 // we must catch all exceptions to ensure that all observers are notified.
71 // we pass the exception to the observer so that it can handle it.
72 // to make sure it doesn't result in another throwable, we catch it here agian.
73 try {
74 $interested_observer->updateFailed($e, $event, $data);
75 } catch (Throwable) {
76 // we can't do anything here.
77 }
78 }
79 }
80 }
81
82 protected function initObserverGroup(string $group): void
83 {
84 if (!isset($this->observer_groups[$group])) {
85 $this->observer_groups[$group] = [];
86 }
87 }
88}
attach(Observer $observer, Event $event)
Definition: Subject.php:39
detach(Observer $observer, Event $event=Event::ALL)
Definition: Subject.php:46
@ ALL
event string being used if
getId()
Unique identifier of the implementing event-listener.