Rendering HTML Paragraphs with Polymorphs in PHP 5

In this second article in a seven-part series on building polymorphs in PHP 5, I provide you with another example of how to do this by way of a simple interface. For this tutorial, I decided to work with objects that are responsible for rendering different HTML elements, such as div and paragraphs, but naturally it’s possible to construct these types of object for different purposes as well.

One of the most powerful foundations of efficient software development is Polymorphism. This is true even though many inexperienced developers do not see how relevant this key pillar of programming actually is to building solid applications.

In PHP 5, which as you know is best for constructing web-based programs, Polymorphism can be achieved successfully only at the class level, through a clever use of Inheritance. This is due to the weakly-typed nature of the language itself.

However, this limitation isn’t a real obstacle that prevents PHP developers from exploiting the benefits of code reuse. In reality, thanks to the highly-improved object model available in PHP 5, it’s feasible to build polymorph classes by means of two well-differentiated approaches. One of these is naturally by using parent classes in their different flavors, and the other one relies on utilizing interfaces.

The good news is that the language permits you to combine these approaches within the same class or classes, thus getting the best of both worlds. But let me clarify this concept for you with a simple example. Say that you’re building a model class whose main task is to perform CRUD operations against a selected database.

Quite possibly, you’ll be deriving subclasses from the parent model to implement some specific methods within these children to interact with a particular database. In a case like this, these polymorph subclasses also could be implementers of the “Countable” and “Seekable” interfaces included with the Standard PHP Library, for instance for counting and seeking database records. Pretty useful, right?

The best way to understand how to build polymorph classes in PHP 5 is through some basic examples. In the introductory chapter of this series I explained how to achieve Polymorphism with interfaces, since in that tutorial I demonstrated how to construct a polymorph class for rendering HTML divs on the browser. This class was a simple implementer of an interface called “HTMLElement,” which naturally declared some generic methods at the top of the hierarchy.

But definitely, it’d be instructive to extend this initial example and show how to use this same interface for creating polymorph objects capable of constructing HTML paragraphs. That’s exactly what I’m going to do in the next few lines, so to learn more on this process, start reading!

{mospagebreak title=Review: constructing polymorph objects via interfaces}

Before I begin explaining how to render HTML paragraphs by using polymorph objects that implement a determined interface, it’d be helpful to recall the example developed in the previous installment of the series. That example demonstrated how to work with this kind of object for building HTML divs.

Having said that, here’s the definition of the interface that outlines the structure of generic HTML elements. Take a look at it:

 

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 shown above, the structure of the “HtmlElement” interface is extremely simple to follow. It only defines four generic methods for assigning the “id” and “class” attributes to a given HTML element, as well as for setting its contents and rendering it to the browser.

As you may know, due to the abstract nature of interfaces in PHP 5, there’s not much more that can be said about this one in particular, so it’s time to show the definition of the class that’s actually an implementer of the earlier “HtmlElement.”

Here’s the complete source code of this polymorph class, which is charged with building HTML divs:

 

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>’;

 

}

}  

Well, you’ll have to agree with me that the driving logic of the above “Div” class is very easy to grasp. All it does is implement the four methods declared by the “HtmlElement” interface to construct div elements.

Despite the rather primitive definition of this sample class, it demonstrates how interfaces can be used in PHP 5 for building polymorph objects in a truly painless way.

And now that you hopefully understand how the ”Div” class does its thing, here’s a code fragment that shows how to use it for displaying a simple div on screen:

 

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

There you have it. Thanks to the chainable API exposed by the “Div” class, rendering an HTML div on screen is as simple as writing a couple of lines of code, aside from the corresponding comments.

Well, at this point you may have realized how useful interfaces can be for  achieving Polymorphism in PHP 5. So, next I will develop another example similar to the previous one, but this time the class that will implement the previous “HtmlElement” interface will be responsible for displaying some HTML paragraphs.

Want to learn how this will be accomplished? Then simply click on the link below and read the following section.

{mospagebreak title=Building a polymorph class that constructs HTML paragraphs}

As I said in the section that you just read, it’d be pretty instructive to develop an example that depicts how to use the “HtmlElement” interface shown before for building a polymorph class that renders HTML paragraphs instead of plain divs.

The purpose of this example is to illustrate how two classes that implement the same interface can reveal different behavior, even when they have the same methods. But wait a minute! Doesn’t this sound like the definition of polymorph objects in PHP 5? Of course it does. And to demonstrate this concept more clearly, below I included the definition of the class that will display the aforementioned HTML paragraphs on the browser.

Study its definition, please:

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>’;

 

}

}

As you can see, the signature of the whole new “Paragraph” class looks quite similar to the one that constructs div elements, except for some subtle differences, such as the default values assigned to its properties and the definition of its “render()” method. 

Logically, this must be that way, because the class renders paragraphs and not divs. This demonstrates that two or more classes that implement the same interface can act completely differently when their homonymous methods are invoked in exactly the same context. 

Simply studying the signature of the previous “Paragraph” class should be enough to let you grasp the underlying logic behind building polymorph objects via interfaces. But if you still have some doubts about this topic, in the section to come I’m going to create a short script that will display an HTML paragraph on the browser. 

To see how this script will be coded, read the next few lines.

{mospagebreak title=A polymorph class in action}

If you’re anything like me, then most likely you’ll want to see how the “Paragraph” class defined in the previous segment can be put to work in a concrete context. With that idea in mind, below I coded a simple script that shows how to display a basic HTML paragraph on screen by using the chainable API of the aforementioned class.

Here’s the script in question:

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

The purpose in coding a script like this is not showing how to create basic paragraphs here and there; that would be pointless. Here, the relevant thing is the approach used for building polymorph objects, which involves a simple interface and a couple of implementer classes.

Of course, since in PHP 5 classes can implement multiple interfaces, it’s possible to take advantages of Polymorphism by inheriting generic methods from several sources, even when these methods must be concretely implemented by the pertinent classes.

Final thoughts

In this second episode of this series, I provided you with another concrete example that showed how to build polymorph objects in PHP 5 by way of a simple interface. For this tutorial, I decided to work with objects that are responsible for rendering different HTML elements, such as div and paragraphs, but naturally it’s possible to construct this type of object for different purposes as well.

In the upcoming part, I’m going to explore another approach for achieving Polymorphism in PHP 5. You’ll surely find it very familiar, since it will involve working with abstract classes.

Don’t miss the next tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan