Using Abstract Classes to Build Polymorphs in PHP 5

In this third part of a seven-part series, I demonstrate how to build polymorph objects using abstract classes in PHP 5. As you’ll see, it’s a pretty straightforward process that can be tackled with relative ease.

Learning how to build polymorph objects in PHP 5 is one of those topics that must be tackled sooner or later by those developers who want to expand their skills in using the object-oriented paradigm for creating web applications.

So, if you’re a PHP programmer looking for a friendly guide that shows you how to take advantage of the functionality provided by Polymorphism, then don’t hesitate anymore and start reading this series of articles right away!

In simple terms, there are two approaches that can be used for achieving Polymorphism in PHP 5, due to the weakly-typed nature of the language. The first one consists of defining one or many interfaces whose generic methods are inherited by the class or classes that implement those interfaces. This process is not surprisingly known as “Polymorphism via interfaces.”

The other methodology is certainly the most popular. It’s based upon defining first a parent class, and then deriving as many subclasses as needed from it. These subclasses will reveal different behaviors, even if they implement the same method defined by the corresponding parent.

In the preceding tutorial of this series I demonstrated how to build polymorph objects by using a single interface. In that particular case, the interface declared four methods for outlining the structure of a generic HTML element object. With this interface settled on top of the hierarchy, it was really easy to create two classes that implemented its methods to construct HTML divs and paragraphs in a few steps.

However, as I said before, the most typical way to build polymorph objects in PHP is by way of one or more parent classes. You’ve probably done this hundreds of times before. Anyway, since this approach deserves a closer look, in the next few lines I’m going to show you how to render HTML divs on screen by using a simple abstract class.

Are you ready to learn more about how this will be accomplished? Then, go ahead and begin reading!

{mospagebreak title=Review: building polymorph objects using interfaces}

In the previous article I discussed how to build a couple of polymorph objects by using a simple interface; below, I listed the source code of that interface, along with the pair of sample classes that implement its generic methods.

First, take a look at the definition of the interface, which comprises the bare bones structure of an HTML element. Here it is:

interface HtmlElement

{

// assign id attribute to HTML element

public function setId($id = ”);

 

// assign class attribute to HTML element

public function setClass($class = ”);

 

// set content for HTML element

public function setContent($content = ”);

 

// render HTML element

public function render();

}

As you can see, there’s nothing special or spectacular about the way that the “HtmlElement” interface has been defined, because all that it does is declare four methods, which of course must be implemented by one or more classes to render specific HTML elements.

Now that you’ve learned how this interface was built initially, it’s time to show the definitions of the classes that are implementers of it. The first one is responsible for displaying divs, while the second one is charged with building basic paragraphs.

Here’s the signature of the first of these classes, not surprisingly called “Div:”

class Div implements HtmlElement

{

private $id = ‘divid';

private $class = ‘divclass';

private $content = ‘Default content for the div';

 

// assign id attribute to div element

public function setId($id = ”)

{

if ($id !== ”)

{

$this->id = $id;

}

return $this;

}

 

// assign class attribute to div element

public function setClass($class = ”)

{

if ($class !== ”)

{

$this->class = $class;

}

return $this;

}

 

// set content for div element

public function setContent($content = ”)

{

if ($content !== ”)

{

$this->content = $content;

}

return $this;

}

 

// render div element

public function render()

{

return ‘<div id="’ . $this->id . ‘" class="’ . $this->class . ‘">’ . $this->content . ‘</div>';

 

}

}  

If you take a closer look at the above class, then you’ll realize how it works. It implements the four generic methods defined by the “HtmlElement” interface for constructing simple divs.

Undoubtedly, analyzing the “Div” class on its own is a pretty boring process that doesn’t deserve any special attention. However, things get much more interesting if you look at the definition of the following class, which is also an implementer of the “HtmlElement” interface and uses its methods for constructing some paragraphs.

Here’s the referenced class:

class Paragraph implements HtmlElement

{

private $id = ‘parid';

private $class = ‘parclass';

private $content = ‘Default content for the paragraph';

 

// assign id attribute to paragraph element

public function setId($id = ”)

{

if ($id !== ”)

{

$this->id = $id;

 }

return $this;

}

 

// assign class attribute to paragraph element

public function setClass($class = ”)

{

if ($class !== ”)

{

$this->class = $class;

}

return $this;

}

 

// set content for paragraph element

public function setContent($content = ”)

{

if ($content !== ”)

{

$this->content = $content;

}

return $this;

}

 

// render paragraph element

public function render()

{

return ‘<p id="’ . $this->id . ‘" class="’ . $this->class . ‘">’ . $this->content . ‘</p>';

 

}

}

In this example, the “Paragraph” class is responsible for displaying HTML paragraphs on screen and nothing else. Regardless of the rather simple logic that drives this particular class and its counterpart “Div,” though, the most important thing to stress here is that even when both are implementers of the “HtmlElement” interface, they behave differently when their “render()” method gets called.

This shows how easy it is to achieve Polymorphism in PHP 5 using an interface. You’ll understand the process better if you look at the following script, which renders a div and a paragraph on the browser by creating a couple of objects from the aforementioned classes:

// create new instance of Div class

$div = new Div();

// assign attributes and content for div element and display it on the browser

echo $div->setId(‘myid’)

->setClass(‘myclass’)

->setContent(‘This is the new content for the div.’)

->render();

 

// create new instance of Paragraph class

$par = new Paragraph();

// assign attributes and content for paragraph element and display it on the browser

echo $par->setId(‘myid’)

->setClass(‘myclass’)

->setContent(‘This is the new content for the paragraph.’)

->render();

That was easy to code and read, wasn’t it? This code fragment shows clearly how two objects that implement the same “render()” method can behave radically different at runtime, which turns them into true polymorph objects.

Nonetheless, as I mentioned in the introduction, interfaces aren’t the only approach that can be used for achieving Polymorphism in PHP 5. It’s also possible to utilize parent classes to take advantage of the functionality of Inheritance.

If you’re interested in learning how to build polymorph objects via parent classes, in the next section I’m going to show you how to create the same div elements that you saw before, this time by using a base abstract class.

To learn more on this topic, click on the link that appears below and keep reading.

{mospagebreak title=Implementing Polymorphism via abstract classes}

Without a doubt, one of the simplest approaches that can be utilized for building polymorph objects in PHP relies on using parent classes. Basically, this approach requires building a base class on top of the hierarchy, and then deriving from this parent as many subclasses as needed, which permits you to implement in a different manner a method that is common to all of the children.

To grasp this approach more clearly, the first thing that I’m going to do will be defining an abstract class that will encapsulate most of the functionality required for building basic HTML elements.

Once this parent has been properly built, a child class will be spawned from it, which will be specially refined for rendering HTML divs. Not too difficult to grasp, right?

Having outlined my plan, here’s the definition of the aforementioned abstract class. Take a look at it:

abstract class HtmlElement

{

protected $id = ‘myid';

protected $class = ‘myclass';

protected $content = ‘Default content for the HTML element';

 

// assign id attribute to HTML element

public function setId($id = ”)

{

if ($id !== ”)

{

$this->id = $id;

}

return $this;

}

 

// assign class attribute to HTML element

public function setClass($class = ”)

{

if ($class !== ”)

{

$this->class = $class;

}

return $this;

}

 

// set content for HTML element

public function setContent($content = ”)

{

if ($content !== ”)

{

$this->content = $content;

}

return $this;

}

 

// render HTML element (not implemented)

abstract function render();

}

Certainly, understanding how this abstract class does its business isn’t rocket science. As you can see, it looks very similar to the sample classes shown in the previous segment, with the exception of some subtle differences worth mentioning here. First, this is an abstract class, so it can’t be instantiated. And second, it does implement its two setters, but no logic has been added to its “render()” method.

This makes it really easy to derive a subclass from “HtmlElement” that gives a concrete implementation to this particular method. That’s exactly what the following “Div” class does. Look at it:

// define Div class (subclass of HtmlElement class)

class Div extends HtmlElement

{

// render div element

public function render()

{

return ‘<div id="’ . $this->id . ‘" class="’ . $this->class . ‘">’ . $this->content . ‘</div>';

 

}

}

Since the abstract “HtmlElement” class encapsulates almost all the functionality required for constructing simple HTML element objects, the definition of its subclass “Div” is actually very short. In this case, the “render()” method is implemented only with the purpose of returning to client code the HTML necessary to display a div on screen.

At this stage everything looks pretty good. I recreated a typical scenario where a subclass is responsible for adding logic to a method defined by its corresponding parent, which happens to be an abstract class. Nonetheless, at this point it’d be premature to say that this subclass is truly a polymorph, since it’s necessary to derive another child class that implements the “render()” method in a different way.

But actually I’m getting ahead of myself, since this process will be tackled in the upcoming part of the series. Meanwhile, it’d be desirable to build a script that shows how to use the previous “Div” class.

Since that script will be coded in the final section, I suggest you read the following segment.

{mospagebreak title=Using the Div subclass}

As I expressed in the preceding segment, I’d like to end this tutorial by showing you how to use the “Div” class built previously, so you can see how simple this process can be.

Here’s an example script that creates an instance of the corresponding “Div” class and uses the “render()” method for displaying a div on the browser:

// create new instance of Div class

$div = new Div();

// assign attributes and content for div element and display it on the browser

echo $div->setId(‘divid’)->setClass(‘divclass’)->setContent(‘This is the new content for the div.’)->render();

There you have it. As seen above, it’s extremely easy to create and output a div on screen, thanks to the chainable interface of the “Div” class. Of course, this example script assumes that the definition of the base “HtmlElement” class has been previously included, so make sure to do that if you wish to try this example using your own testing web server.

Finally, feel free to edit all of the code samples included in this tutorial, so you can arm yourself with a more thorough background in building polymorph objects that rely on the use of abstract classes.

Final thoughts

In this third installment of the series, I demonstrated that building polymorph objects using abstract classes in PHP 5 is a pretty straightforward process that can be tackled with relative ease. Well, admittedly I’m halfway to completing the demonstration process; at this point I’ve built a subclass that inherits part of the functionality from its abstract parent and builds HTML divs.

You may be wondering what’s missing in this schema. It’s necessary to derive yet another class from the same parent that behaves differently when its “render()” method gets called.

This topic will be covered in depth in the upcoming tutorial, so now you don’t have any excuses to miss it!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort