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