HomePHP Page 4 - Creating AJAX Requester Objects with Abstract Factory Classes in PHP 5
Demonstrating the functionality of the abstract factory pattern - PHP
The abstract factory pattern can be useful if you’re developing a PHP application that needs to create diverse objects in multiple contexts. If you’re interested in learning the basics of this design pattern, this set of articles might be what you’re looking for. Welcome to the second installment of the series “Using abstract factory classes in PHP 5.” In a step-by-step guide, this series teaches you how to create abstract factory classes in PHP 5 by providing you with a wealth of educational examples on the topic.
The best way to demonstrate the functionality offered by the abstract factory pattern is simply by setting up an instructive example where all the previously defined classes are used in conjunction.
Bearing in mind the strong educational sense of the example in question, below I coded a short script. It illustrates how the two concrete factories that you learned in a previous section are capable of returning the correct type of AJAX objects to client code, depending on the context where they're used.
Here is the sample script:
try{ // instantiate 'SynchronousAjaxRequesterFactory' object // (works in the 'synchronous' context) $factoryInstance=new SynchronousAjaxRequesterFactory(); $syncRec1=$factoryInstance->createAjaxTextRequester(); $syncReq1->send(); $syncReq2=$factoryInstance->createAjaxXmlRequester(); $syncReq2->send(); // instantiate 'AsynchronousAjaxRequesterFactory' object // (works in the 'asynchronous' context) $factoryInstance=new AsynchronousAjaxRequesterFactory(); $asyncReq1=$factoryInstance->createAjaxTextRequester(); $asyncReq1->send(); $asyncReq2=$factoryInstance->createAjaxXmlRequester(); $asyncReq2->send(); } catch(Exception $e){ echo $e->getMessage(); exit(); }
As illustrated above, after the first synchronous factory class has been instantiated, it makes sure that only synchronous AJAX objects are returned to client code, following the logic implemented by the abstract factory pattern. Similarly, once a new instance of the asynchronous factory class is created, naturally only asynchronous AJAX objects will be spawned. Simple and efficient!
At this stage, I believe that the example shown above should give you an accurate idea of how the abstract factory pattern works. So go ahead with this recently-acquired background and start building your own abstract factory classes!
Final thoughts
Sadly, this is the end of this article. However, the overall experience has been educational, since you learned how to use the abstract factory pattern in PHP 5, in order to create AJAX objects that depend on a predefined context.
But do you think this journey is over? Not at all, because in the last installment of this series, I'm going to show you how to use this useful pattern to build programmatically online forms. You won't want to miss it.