If you're anything like me, you want to see how the group of sample classes defined in the previous section can be used together in a practical example. In this case, I'm going to code a short script, which hopefully will illustrate how each of the factory classes that you leaned before can be statically called to create different data saving objects. Since the two pertinent "product" classes that work with a specified "object" context accept an object as their unique input parameter, I will define a sample "User" class which will be utilized by these classes. Here is the corresponding signature for the "User" class: // define 'User' class If you study the definition of the previous "User" class, surely you'll realize that it is very easy to grasp, so I'm not going to waste your time with irrelevant explanations about how it functions. Instead, I'd like you to pay attention to the following script, which demonstrates how all the prior factory classes can be used to spawn different types of data saving objects. The corresponding code sample is as follows: try{ /* // create cookie string saver object /* // create file object saver object /* // create cookie object saver object catch(Exception $e){ As shown in the above script, all the factory classes are called statically (note the use of the :: scope resolution operator) with the purpose of creating distinct data saving objects. For each specific case, the script also displays the corresponding outputs, something that helps in understanding more clearly how the factor pattern works. I encourage you to use all the factory and product classes defined in the course of this article and introduce your own modifications to them. This will give you a more robust background in this particular pattern. To wrap up In this second article of the series, I provided you with another hands-on example surrounding the implementation of the factory design pattern with PHP 5. Nevertheless, this educational journey hasn't ended yet, since I'm going to finish this series by showing you how to use this handy pattern in a real world situation: building a set of context boxes, which can be easily included into any web page. The experience sounds really interesting, so I hope to see you in the last part!
blog comments powered by Disqus |
|
|
|
|
|
|
|