As you'll certainly recall from the previous section, I said that the best way to understand how the interpreter pattern works is by developing a concrete example, where all the classes that were defined previously are put to work together. Basically, what is expected here is that the interpreter class must be capable of parsing the appropriate commands passed in to its "interpret()" method, in this way displaying information about one or more user objects. So, considering the expectations that you may have concerning the implementation of the previous interpreter class, below I included a short script, which demonstrates the functionality of this pattern. The corresponding code sample is as follows: try{ // displays postal address of first user /* // display email of first user /* // display name of second user /* // display postal address of second user /* // display email of second user /* // display name of last user /*
/* // display email of last user /* // send a erroneous command to the interpreter /* throws an exception with the following message: // display data about all users at once /* If you study the above example, then you'll realize how powerful the interpreter class can be when it comes to displaying information about one or more users. As you can see, the script begins by creating some fictional users, which are saved onto an instance of the "UserSaver" class, and then uses the interpreter object to show data about each one of the stored users. Of course, this entire process is performed by sending out to the interpreter the correct user commands. This means that this simple implementation of the pattern in question can be really helpful for building a basic abstraction layer for handling user data. Quite good, isn't it? As homework, try adding more users to the previous example, and see what happens when you send erroneous commands to the interpreter. Trust me, the experience can be truly fun! Final thoughts In this first tutorial of the series, I walked you through the basics of how to implement the interpreter pattern in PHP 5. However, this is only the beginning, because in the next part I'm going to show you how to use this handy pattern in conjunction with some string processing classes. Now that you're warned, are you going to miss it? I hope not!
blog comments powered by Disqus |
|
|
|
|
|
|
|