Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement a full Observer pattern in PHP
    text
    copied!<p>An <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="noreferrer">Observer Design Pattern</a> is the solution to loosely coupling objects so they can work together. In PHP you can easily implement this using just <a href="https://github.com/elliot/observer" rel="noreferrer">two classes</a>.</p> <p>Basically, you have a subject which is able to notify and update a list of observers of its state changes.</p> <p><strong>The problem I'm trying to solve is to know how to handler alerting the observers about different states of the object they are watching.</strong></p> <p>For example, lets say we have a file upload class to which we attach a logging class, websockets class, and a image resize class. Each of these classes that are watching want to know about different events in the upload process.</p> <p>This file upload class might have three places where it needs to notify the classes listening that something has happend.</p> <ul> <li>Error With Upload (alert logging class)</li> <li>Upload success (alert websockets class)</li> <li>Upload success and is image file (alert image resize class)</li> </ul> <p>This is a very basic example, but how do you handle multiple events that different observers may need to know about? Calling notifyObservers() alone wouldn't be enough since each observer needs to know what it is being notified about.</p> <p>One thought is that I could state with the call what type of event is being observed:</p> <pre><code>$this-&gt;notifyObservers('upload.error', this); </code></pre> <p>However, that would mean I would have to add custom switching to the observers themselves to know how to handle different events.</p> <pre><code>function observe($type, $object) { if($type === 'upload.error') $this-&gt;dosomething(); elseif($type === 'something.else') $this-&gt;otherthing(); ...etc... } </code></pre> <p>I find that very ugly as it starts to couple the observers back to the class they are observing.</p> <p>Then again, if I just notify Observers without passing any information about what event just happens - they have to guess themselves what is going on which means more if() checks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload