Login

Using Different Objects in the Same Script for Polymorphs in PHP

Welcome to the final part of a seven part series on building polymorphs in PHP. In a friendly fashion, this series gets you started constructing polymorph classes specifically in PHP 5. It shows you how to accomplish this by using first interfaces, then parent classes, and finally a proper combination of both.

And now that you’ve been introduced to the main goal of this group of tutorials, it’s time to review the topics discussed in the last one. In that article I explained how to build a couple of polymorph classes; both of them inherited structure from a simple interface and functionality from an abstract class responsible for rendering generic HTML elements.

Also, it’s necessary to recall that each of the classes constructed a specific HTML element through a common method called “render().” They also parsed its contents via another method, named“parseContent(),” which was inherited from the pertinent interface.

However, analyzing the construction of these sample classes separately would not be very helpful for understanding their polymorph nature. To solve this issue, in this final chapter of the series I’m going to develop a couple of scripts where the classes will be put to work together.

Now, it’s time to tackle the last part of this hopefully educational exercise in building polymorph classes with PHP 5. Let’s get going!

Naturally, before I demonstrate how the pair of polymorph classes built in the previous tutorial can be used within the same script, it’d be helpful to show their respective definitions and reintroduce the signature of the interface and the abstract parent class from which they inherit both structure and functionality.

Here’s source code of the interface that declares a single method called “parseContent().” Take a look at it:

// define interface Parser

interface Parser

{

public function parseContent();

}

As I said before, the “Parser()” interface declares the signature of only one method, so there’s not much to be said about it for the moment. Let’s look at the definition of the following abstract parent class, which encapsulates enough functionality to build generic HTML elements:

// define abstract class HtmlElement

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();

}

As you can see, the above “HtmlElement” abstract class simply implements a few straightforward methods for outlining the behavior of generic HTML elements, so I won’t spend additional time explaining the details of its driving logic.

Instead, now that you hopefully recalled how this class functions, let me show you the definitions of the polymorph classes that implement the earlier “Parser” interface and are also derived from the parent class that you just saw.

Definitely, grasping the driving logic of the two polymorph classes isn’t rocket science, right? As you can see, they’re simple implementers of the pertinent “Parser” interface, in addition to being subclasses of the parent “HtmlElement.” This condition lets them take advantage of these two structures simultaneously. Not bad, eh?

So far, so good. At this stage, you’re hopefully familiar with the way that these two polymorph classes do their business. So it’s time to develop some sample scripts that show how to use them in tandem for rendering HTML divs and paragraphs.

In the section to come, I’m going to create the first of those scripts, so read the following segment. I’ll be there, waiting for you.

{mospagebreak title=Rendering HTML divs and paragraphs within the same script}

Without a doubt, the best way to understand the polymorph nature of the subclasses shown in the previous segment is by means of some functional code samples that show how those classes expose a different behavior when their respective “render()” and “parseContent()” methods are invoked within the same script.

Below I included such a script, so I suggest you to look at it closely:

// create new instance of Div class

$div = new Div();

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

echo $div->setId(‘divid’)

->setClass(‘divclass’)

->setContent(‘<html>Testing the div class.</html>’)

->parseContent()

->render();

// create new instance of Paragraph class

$par = new Paragraph();

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

echo $par->setId(‘parid’)

->setClass(‘parclass’)

->setContent(‘<p>Testing the paragraph class.</p>’)

->parseContent()

->render();

Perhaps it’s unnecessary to clarify this, but if you run the above script on your own testing web server, you’ll see that a div and a paragraph will be outputted to the browser. Even though this particular example is rather simplistic, it shows in a nutshell how easy it is to construct a couple of polymorph classes by relying on an interface and an abstract class simultaneously.

Are you not convinced yet of the real polymorph behavior of these sample classes? Well, of course you have the right to think that way. However, since my goal here is to dissipate all of your doubts regarding this subject, in the final section of this tutorial I’m going to create another example for you, so you can finally be convinced.

Now, to see how this concluding example will be developed, click on the link that appears below and read the following segment.

{mospagebreak title=Passing a different argument to the parseContent()method of the polymorph classes}

I’d like to finish this last part of the series by coding another simple example that shows how the “render()” and “parseContent()” methods that belong to the previous “Div” and “Paragraph” classes can behave radically differently, even when called in the context of the same script.

This particular hands-on example looks like this:

// create new instance of Div class

$div = new Div();

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

echo $div->setId(‘divid’)

->setClass(‘divclass’)

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

->parseContent()

->render();

// create new instance of Paragraph class

$par = new Paragraph();

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

echo $par->setId(‘parid’)

->setClass(‘parclass’)

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

->parseContent()

->render();

Hopefully with this final example, you’ll see for yourself that the “Div” and “Paragraph” classes shown previously are true polymorph structures. To demonstrate this concept more clearly, I modified the contents that are inputted into the “parseContent()” method of the classes, which will produce completely different results.

Feel free to edit all of the code samples included in this tutorial. Doing so will help give you a better grounding in building polymorph objects in PHP 5.

Final thoughts

It’s hard to believe, but we’ve come to the end of this series. Hopefully this group of tutorials has been insightful for you. You learned how to achieve Polymorphism in PHP 5, first by using interfaces, then via abstract classes, and finally by combining these two structures simultaneously.

At first glance, and particularly for developers taking their first steps in PHP-based web development, it seems that building polymorph objects is rather a pointless task. However, Polymorphism is indeed a powerful paradigm that will help you build solid, well-structured object-oriented applications.