The introduction you read was aimed at providing you with an easy-to-grasp definition of the Observer pattern. As with many concepts related to PHP programming, things become clear only after satisfying the appetite for concrete code. In consonance with this, I’ll start with a simple example, which defines two classes that manipulate PHP strings. Take a look at the corresponding class definitions: // define 'MessageConverter' class As you can see, the two classes that I built above implement a simple mechanism that saves uppercased messages to a given text file. The first class, “MessageConverter,” is responsible for converting the input string passed as argument to uppercase, after which it returns the uppercased message to the calling code. Regarding the “MessageSaver” class, its functionality is really simple. It takes up objects of type “MessageConverter” and saves their messages to a text file, after checking whether the messages in question contain prohibited words or are of an inappropriate length. In both cases, the class will trigger the corresponding exceptions, notifying of the pertinent errors. Due to the simplicity of this example, let’s see how the above classes can be put to work quickly. Take a look at the following code snippet: try{ As shown above, the two classes seem to work seamlessly, and hopefully at the end of the script, the input message passed as a parameter will be saved in uppercase to the specified text file via the “save()” method. Also, it should be noted that these classes act like true independent components, since they have a well defined scope, and don’t overlap each other. What else can we ask for? Well, if you’re going to keep this trivial message-saving application untouched for a long time, then take a deep breathe and congratulate yourself for building such an efficient system. However, say you want to add some kind of error logging module to the application, to keep track of all the errors that will occur when offending messages are passed to the “MessageSaver” class. Sounds like a simple addition, right? In the next section I’ll show you how to add a basic error logger to the previous application, and hopefully you’ll see how the Observer pattern can be applied to solving some problems associated with the scope of the objects involved. Please keep on reading to learn more.
blog comments powered by Disqus |