Creating AJAX Requester Objects with Abstract Factory Classes in PHP 5

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.

Just in case the abstract factory pattern doesn’t ring any bells for you, let me quickly explain how it works. Basically, when this pattern is applied, there’s an abstract factory class which defines what type of objects should be created by the corresponding concrete factories. On the other hand, these factories implement the required logic to make sure that the correct objects are returned to client code, according to the context where they’re used.

Logically, if you’re anything like me, the above definition may sound rather complex. Taking this into account, in the first article of the series I explained how to use the abstract factory pattern to create different types of DIV elements, in this way showing a concrete case where this pattern can be examined in detail.

Now that you hopefully have a stronger background in how this useful pattern works in PHP 5, I’m going to continue showing you more situations where abstract factory classes can be used properly. More specifically, in this second article of the series, I’m going to demonstrate how to apply the abstract factory pattern to create diverse AJAX HTTP requester objects, which can be used in distinct contexts.

I’m pretty certain that once you read this tutorial, you’ll have a more accurate idea of how to apply this handy pattern in your own PHP applications.

Having already defined the subject of this article, let’s find out together how to use an abstract factory class to create AJAX HTTP requester objects. Let’s begin now!

{mospagebreak title=Working with AJAX HTTP requester objects}

To illustrate in a friendly fashion how the abstract factory pattern can be used to spawn different HTTP requester objects, I’m going to define an abstract factory class which will determine what type of AJAX objects will be created by the corresponding concrete factories.

In this case, I decided to provide this abstract factory with the capability to work with text and XML-based HTTP requester objects. Its definition is as follows:

// define abstract ‘AbstractAjaxRequesterFactory’ class
abstract class AbstractAjaxRequesterFactory{
   abstract public function createAjaxTextRequester();
   abstract public function createAjaxXmlRequester();
}

As you can see, even when the signature for the abstract factory class is brief, it shows clearly the nature of the objects that should be created by two non-abstract factories. In this case, these two concrete factories are responsible for returning to calling code at least two types of requester objects, called “AJAXTextRequester” and “AJAXXmlRequester” respectively.

As you might have guessed, the first requester object will be capable of returning to the client all the server responses as plain text via the corresponding “responseText” property offered by AJAX. The second one will return all the server outputs in XML format, logically, by using the “responseXML” property.

As you’ll probably realize, the two types of HTTP requester objects that must be created by the corresponding concrete factories are pretty straightforward. Therefore let me move on and show you the respective signatures for these factories, which will be created as subclasses of the abstract one.

Having said that, take a look at the following child classes, which are responsible for spawning the two kinds of HTTP requester objects mentioned before. Here they are:

 // define concrete ‘SynchronousAjaxRequesterFactory’ class
class SynchronousAjaxRequesterFactory extends AbstractAjaxRequesterFactory{
   private $context=’synchronous';
   public function createAjaxTextRequester(){
     return new SynchronousAjaxTextRequester();
   }
   public function createAjaxXmlRequester(){
     return new SynchronousAjaxXmlRequester();
   }
}
// define concrete ‘AsynchronousAjaxRequesterFactory’ class
class AsynchronousAjaxRequesterFactory extends
AbstractAjaxRequesterFactory{
   private $context=’asynchronous';
   public function createAjaxTextRequester(){
     return new AsynchronousAjaxTextRequester();
   }
   public function createAjaxXmlRequester(){
     return new AsynchronousAjaxXmlRequester();
   }
}

After defining the couple of concrete factory classes listed above, I’m pretty certain that you see more clearly the kind of HTTP requester objects created by each one of them.

With reference to the first factory class, you can see that it works on the "synchronous" context and logically must spawn only synchronous AJAX objects. Meanwhile, the signature of the second factory class demonstrates that only asynchronous objects will be returned to client code. That was pretty simple to grasp, wasn’t it?

Besides, you should notice that whether a factory class is used in a “synchronous” or “asynchronous” context, in both cases it’s capable of creating text-based or XML-based requester objects.

Well, having explained how each concrete factory class works in its corresponding context, I think it’s a good time to move forward and proceed to show the respective definitions for all the classes that are tasked with spawning AJAX objects.

Of course, the signatures that correspond to all these brand new classes will be covered in the next few lines, thus I recommend that you click on the link that appears below and keep reading.

{mospagebreak title=Completing the schema imposed by the abstract factory pattern}

To complete the programmatic model established by the abstract factory pattern, the next step that I’m going to take will consist of defining all the context-based classes that were mentioned in the previous section.

As you’ll see in a moment, these classes will be responsible for creating both synchronous and asynchronous AJAX objects, which also will be capable of returning the server responses as plain text and XML.

This being said, here are the corresponding definitions for the previously referenced classes. Please take a look at them:

// define ‘SynchronousAjaxTextRequester’ class
class SynchronousAjaxTextRequester{
    private $url=’default_url.php';
    private $callbackFunc=’defaultFunc';
    // send http request
    public function send(){
      $js.=<<<EOD
  <script>
    
var xmlobj=null;
    
try{
     
xmlobj=new XMLHttpRequest();
   
}
   
catch(e){
     
try{
       
xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
     
}
     
catch(e){
       
alert(‘AJAX is not supported by your browser!’);
     
}
   
}
   
xmlobj.onreadystatechange=function(){
   
if(xmlobj.readyState==4){
     
if(xmlobj.status==200){
       
eval(‘$this->callbackFunc’+'(xmlobj.responseText)’);
     
}
   
}
  }
 
//xmlobj.open(‘GET’,’$this->url’,false);|
 
//xmlobj.setRequestHeader(‘Content-Type’,’text/html;
charset=UTF-8′);
 
//xmlobj.send(null);
</script>          
EOD;
      echo $js;
      }
}

// define concrete ‘SynchronousAjaxXmlRequester’ class
class SynchronousAjaxXmlRequester{
   private $url=’default_url.php';
   private $callbackFunc=’defaultFunc';
   // send http request
   public function send(){
     $js.=<<<EOD
  <script>
   
var xmlobj=null;
    try{
     
xmlobj=new XMLHttpRequest();
   
}
   
catch(e){
     
try{
       
xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
     
}
     
catch(e){
       
alert(‘AJAX is not supported by your browser!’);
     
}
    
}
   
xmlobj.onreadystatechange=function(){
     
if(xmlobj.readyState==4){
       
if(xmlobj.status==200){
         
eval(‘$this->callbackFunc’+'(xmlobj.responseXML)’);
       
}
     
}
    
}
   
//xmlobj.open(‘GET’,’$this->url’,false);
   
//xmlobj.setRequestHeader(‘Content-Type’,’text/xml;
charset=UTF-8′);
   
//xmlobj.send(null);
 
</script>          
EOD;
      echo $js;
      }
}

// define concrete ‘AsynchronousAjaxTextRequester’ class
class AsynchronousAjaxTextRequester{
   private $url=’default_url.php';
   private $callbackFunc=’defaultFunc';
   // send http request
   public function send(){
     $js.=<<<EOD
 
<script>
   
var xmlobj=null;
   
try{
     
xmlobj=new XMLHttpRequest();
   
}
   
catch(e){
     
try{
       
xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
      
}
      
catch(e){
       
alert(‘AJAX is not supported by your browser!’);
     
}
    
}
   
xmlobj.onreadystatechange=function(){
     
if(xmlobj.readyState==4){
       
if(xmlobj.status==200){
         
eval(‘$this->callbackFunc’+'(xmlobj.responseText)’);
       
}
     
}
   
}
   
//xmlobj.open(‘GET’,’$this->url’,true);
   
//xmlobj.setRequestHeader(‘Content-Type’,’text/html;
charset=UTF-8′);
   
//xmlobj.send(null);
 
</script>          
 
EOD;
      
echo $js;
      }
}

// define concrete ‘AsynchronousAjaxXmlRequester’ class
class AsynchronousAjaxXmlRequester{
   private $url=’default_url.php';
   private $callbackFunc=’defaultFunc';
   // send http request
   public function send(){
     $js.=<<<EOD
 
<script>
   
var xmlobj=null;
   
try{
     
xmlobj=new XMLHttpRequest();
   
}
   
catch(e){
     
try{
       
xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
     
}
     
catch(e){
       
alert(‘AJAX is not supported by your browser!’);
     
}
    
}
   
xmlobj.onreadystatechange=function(){
     
if(xmlobj.readyState==4){
       
if(xmlobj.status==200){
         
eval(‘$this->callbackFunc’+'(xmlobj.responseXML)’);
       
}
     
}
   
}
   
//xmlobj.open(‘GET’,’$this->url’,true);
   
//xmlobj.setRequestHeader(‘Content-Type’,’text/xml;
charset=UTF-8′);
   
//xmlobj.send(null);
 
</script>          
 
EOD;
      echo $js;
      }

Okay, don’t feel intimidated by the rather lengthy definitions of all the previous classes, since the logic that stands behind each one of them is actually quite easy to follow. If you look at the first two, you’ll see clearly that they work in the “synchronous” context, and obviously are tasked with creating AJAX objects that trigger synchronous requests.

The only difference between these classes is that the first one receives server responses as plain text, while the second one accepts server outputs in XML format. Quite simple to understand, right?

Now, with reference to the other two remaining classes, you can see that they were conceived to work in an “asynchronous” context, and logically take care of sending asynchronous requests to the web server. In addition, they are also capable of receiving server responses as plain text and XML.

All right, now that you have seen how all the previous AJAX classes were defined in consonance with a predefined context, it’s time to develop an example so you can understand more easily how the concrete factory classes that you learned before are capable of returning the correct AJAX objects to client code.

The experience will be instructive. Please read the following section to see how this example will be created in a few simple steps.

{mospagebreak title=Demonstrating the functionality of the abstract factory pattern}

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.

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort