Implementing the Stage Pattern in PHP 5

Updating modules of a web application can be quite a chore, especially when classes are involved. Wouldn’t it be easier if there were a class that could update itself depending on its context? Fortunately there is. It’s called the Stage pattern. This is the first part of a two-part series that introduces you to that pattern and its uses.

Introduction

It’s quite probable that during your life as a PHP developer, you have found yourself updating specific modules of a given web application (or in the worst case, the entire application), since the context where it was originally conceived to work has changed noticeably.

Naturally, if this situation sounds familiar to you, then you’ll know that updating certain parts of an application can be an annoying, time-consuming process. it can be even worse if you have to deal with other issues apart from the ones related to coding, such as suiting deadlines, solving “creative” differences between members of the same development team, and so forth.

Thus, considering all the possible problems that can emerge when a particular PHP application must be updated, you try to write code that is highly maintainable and easy to update. However, if I translate the aforementioned scenario to the terrain of object-oriented programming, sometimes it happens that one or more PHP classes need to be updated according to the modifications introduced into the context where they were initially designed to work.

From a developer’s point of view, this updating process can be difficult, particularly if the application that needs to be modified is comprised of a considerable number of interrelated classes. Therefore, the question that comes up here is: is there any programmatic mechanism that allows you to create a class that changes the way it works, according to the variations incorporated into its environment?

Fortunately, the answer to the previous question is an emphatic yes! In the huge area of pattern-based programming, there’s one pattern called “Stage” that provides developers with a handy mechanism for building a class that’s capable of modifying its behavior in response to the changes introduced into its environment. Indeed, this sounds pretty interesting, right?

Nevertheless, at least at first glance, the definition of the “Stage” pattern seems hard to grasp, which implies that the pattern in question has to be addressed from a practical point of view. In doing so, you’ll have a much better idea of how it works, and eventually how it can be applied in concrete cases.

Therefore, assuming that the stage pattern has already caught your attention, over the course of this two-part series, I’m going to introduce its key concepts, and logically show you how to implement it with copious code samples.

At the end of this series, you should be equipped with a decent background in how to include the stage pattern in your own PHP applications, aside from expanding your overall skills in pattern-based programming. So, are you ready to dive deeper into the implementation of this handy pattern? Let’s begin now!

{mospagebreak title=Creating the programmatic model of the state pattern}

A good place to start demonstrating the functionality provided by the stage pattern is with defining what I call a “target” class. As you’ll see for yourself in a moment, this class will be capable of modifying its behavior according to the variations introduced into its working environment.

Basically, the previously mentioned target class will be tasked with creating simple DIV elements, which will have their “overflow” CSS property set to a value of “hidden” by default. However, if it happens that the context where these DIVs will be used eventually changes, and in addition, the contents wrapped by them grows in size, then the DIVs will modify their overflow property to “scroll.”

Undoubtedly, this is a good example of a class that modifies its behavior in response to changes occurring inside its context; this precisely reflects the schema dictated by the stage pattern.

Okay, now that I have explained how I plan to illustrate the functionality of the stage pattern, please examine the signature of the “Div” class below, which as I stated previously, is responsible for displaying regular DIVs.

The definition for this brand new class is as follows: 

// define ‘Div’ class
class Div{
   private $data=’default_data';
   private $id=’divid';
   private $class=’divclass';
   public function __construct(){}
   // set Div data
   public function setData($data){
     if(!preg_match("/[a-zA-Z0-9]+/",$data)){
       throw new Exception(‘Invalid DIV data has been
supplied.’);
     }
     $this->data=$data;
   }
   // set Div Id
   public function setId($id){
     if(!preg_match("/^[a-z]+$/",$id)){
       throw new Exception(‘Invalid DIV id has been supplied.’);
     }
     $this->id=$id;
   }
   // set Div class
   public function setClass($class){
     if(!preg_match("/^[a-z]+$/",$class)){
       throw new Exception(‘Invalid DIV class has been
supplied.’);
     }
     $this->class=$class;
   }
   // get Div data
   public function getData(){
     return $this->data;
   }
   // get Div id
   public function getId(){
     return $this->id;
   }
   // get Div class
   public function getClass(){
     return $this->class;
   }
}

As you can see, the structure corresponding to the above “Div” class is indeed very easy to follow. The class in question presents the typical modifiers and accessing methods, which come in handy for setting and retrieving the values assigned to its “$data,” $id” and “$class” properties respectively, so I guess you shouldn’t have major problems understanding how it works.

However, as I explained earlier, the previous “Div” class is only a part of the stage pattern, since it can’t change its behavior by itself when the context varies. Therefore it’s necessary to define another class, which will be responsible for controlling the context where the target class is utilized, and eventually change its behavior.

Taking into account that a brand new contextual class has to be defined to complete the programmatic model imposed by the stage pattern, please jump into the following section and keep reading to learn how this class will be created.

{mospagebreak title=Changing the behavior of a target class}

In consonance with the concepts that I deployed in the section that you just read, a brand new class must be built to complete the model dictated by the stage pattern. As you’ll see shortly, this contextual class will be capable of modifying the behavior of the “Div” class that you saw earlier.

But how will this be done? In plain words, if the contents wrapped by a specific DIV are larger than a predefined length, the DIV will switch its “overflow” CSS property to a value of “scroll.” Otherwise, the property in question will keep its original value, which is “hidden.” Sounds simple, right?

Now that you know how this contextual class is going to work, study its corresponding signature. It is as follows:

// define ‘DivContext’ class
class DivContext{
    private $div=NULL;
    private $divOverflow=NULL;
    public function __construct(Div $div){
      $this->div=$div;
    }
    // get ‘Div’ object
    public function getDiv(){
      return $this->div;
    }
    // get (X)HTML markup of ‘Div’ object
    public function getDivHTML(){
      $this->divOverflow=strlen($this->div->getData())
>64?’scroll':’hidden';
      return ‘<div id="’.$this->div->getId().’" class="’.$this-
>div->getClass().’" style="overflow: ‘.$this-
>divOverflow.';">’.$this->div->getData().'</div>';
    }
}

After examining the definition of the above “DivContext” class, you’ll have to agree with me that its functionality is indeed remarkable, regardless of its short signature. As you can see, this brand new contextual class takes up a “Div” object as its unique input parameter and assigns it as a class property.

However, I’d like you to pay attention to the signature of the “getDivHTML()” method, since this method is actually the workhorse of the class. Please notice how the method determines what value for the “overflow” CSS property will be assigned to the target DIV, depending on the length of the contents that will be housed by this containing element.

In this case, there’s a class that will change the way it displays a DIV element on a web page, according to the changes introduced into its context, in this way implementing the so-called stage pattern. Isn’t that interesting?

Okay, at this stage you hopefully grasped the logic that drives the stage pattern, therefore I think it’s an excellent time to move forward and see how the pair of classes previously defined can be put to work in a fully-functional example.

As you might have guessed, this instructive example will be developed in the following section, thus click on the link below and keep reading.

{mospagebreak title=Seeing the stage pattern in action}

As you certainly recall from the previous section, I thought that the best way to understand the functionality provided by the stage pattern is by simply setting up a concrete example where the pair of classes that you learned earlier are put to work in tandem.

Since I consider this a good approach to demonstrate how the pattern in question works, in the next few lines I coded a short script, which shows how a contextual div object is capable of modifying the behavior of a given DIV element, in this case by changing the value of its “overflow” CSS property.

As I explained in the prior section, the aforementioned CSS property will be modified according to the length of the contents included into the target DIV, certainly a condition that is in evidence by the below example.

That being said, please take a look at the following code listing:

try{
   // create new ‘Div’ object
   $div=new Div();
   // set Div properties
   $div->setData(‘This is a sample string that will be included
into the DIV.’);
   $div->setId(‘newid’);
   $div->setClass(‘newclass’);
   // create new ‘DivContext’ object
   $divContext=new DivContext($div);
   // display DIV element (its overflow property has a value of
‘hidden’)
   echo $divContext->getDivHTML();
   // set new data for Div element
   $div->setData(‘This is a sample string that will be included
into the DIV, but in this case the behavior of the DIV object
will change since the length of this data is larger than 64
characters.’);
   // display DIV element (its overflow property has a value of
‘scroll’)
   echo $divContext->getDivHTML();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As demonstrated above, the contextual div object is capable of modifying the value of the “overflow” CSS property that belongs to the target DIV, in this way changing its behavior according to the requirements of a given context.

Now that you grasped the logic that stand behinds the stage pattern, I encourage you to develop your own examples, so you can acquire a more solid background on how this pattern can be used in concrete situations.

Final thoughts

Sadly, we’ve come to the end of this first article of the series. As you saw previously, the stage pattern can be useful in those cases where the context of a particular PHP application is going to change very frequently.

However, if you believe that all the hands-on examples shown in this tutorial are not enough material, I’ve got good news to you. In the last part of the series I’m going to show you how to implement the stage pattern to generate “screen” and printer-friendly versions for a bunch of web documents.

Now that you’ve been warned, are you going to miss it? I hope not!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort