Polymorphs in PHP: Using Interfaces and Abstract Classes to Construct HTML Paragraphs

In this penultimate part of a seven-part series on building polymorphs in PHP 5, I demonstrate how easy it is to build polymorph objects that merge the functionality of abstract classes and the structure of interfaces. The entire creation process is simple enough that you shouldn’t have major problems grasping its underlying logic.

As you may know, most of the mature programming languages that are used nowadays permit developers to implement Polymorphism in one form or another. Undoubtedly C, C++ and Java, for example, are languages that allow you to build polymorph structures, either at function-level or class-level. This characteristic is one of many that make them so powerful.

On the other hand, while PHP doesn’t offer the maturity of big players like Java or C++, and is mainly used for developing web applications rather than creating desktop-based programs, its object model lets developers achieve Polymorphism by using classes and interfaces. This can be very useful for building well-structured object-oriented applications.

However, there’s the possibility that you, as a passionate PHP programmer, are wondering if learning the fundamentals of Polymorphism is really worthwhile. Well, the answer is a resounding yes! By grasping its key concepts you’ll arm yourself with a solid background that will sharpen your existing programming skills.

Of course, if you already had the chance to read the previous part of this series, then you’re probably familiar with building polymorph objects by combining the power of abstract classes and interfaces. In that tutorial I explained how to create a polymorph class that inherited functionality from a base parent, and structure from a simple interface.

This class was responsible for rendering HTML divs through a method called “render().” Even though I discussed in depth how this class worked, this process is still incomplete. It’s necessary to build another sample class that behaves differently when its “parseContent()” method gets called.

Thus, in this sixth part of the series I’m going to build a second polymorph class. It will be tasked with displaying HTML paragraphs by using the interface and the abstract class mentioned above.

Now, it’s time to start learning how to build another polymorph class in PHP 5. Let’s go!

{mospagebreak title=Review: building a polymorph object using an abstract class and an interface}

In the preceding part of this series I went through the development of a polymorph class that inherited its methods from an abstract class and from a single interface. As a review, below I included the complete source code corresponding to this example.

Study the following code sample, please:

// define interface Parser

interface Parser

{

public function parseContent();

}

 

 

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

}

You shouldn’t have much trouble understanding the purpose of defining the previous “Parser()” interface and the complementary “HtmlElement” abstract class. As shown above, when properly combined, these entities provide both functionality and structure for building simple HTML elements that can be easily rendered on the browser.

However, to understand more clearly how these sample entities can be used for achieving Polymorphism in a simple manner, it’s necessary to define a class that implements the inherited “parseContent()” method. The following “Div” class performs this task in only one go:

class Div extends HtmlElement implements Parser

{

public function parseContent()

{

if ($this->content !== ”)

{

$this->content = preg_replace(array(‘/(<html>|<body>)/’, ‘/(</html>|</body>)/’), array(‘<div>’, ‘</div>’), $this->content);

}

return $this;

}

// render div element

public function render()

{

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

 

}

}

There you have it. In this case, the “Div” class adds concrete logic to the “parseContent()” method, so it can be used for stripping unwanted tags from the contents assigned to div elements, such as <html> and <body>. Of course, it’s possible to make this method more complex, but for the moment I’ll keep it  simple.

Now that you’ve learned (or recalled) how the above “Div” class does its thing, here’s a short script that shows how to use it in a concrete case:

// 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>This is the new content for the div.</html>’)

 ->parseContent()

->render();

While this code sample does demonstrate how to use the “Div” class for constructing a simple HTML div, it admittedly comes up short in showing the class’s polymorph nature. What’s wrong with this example? Well, nothing really, but to prove that this class is a polymorph structure, it’s necessary to build another one that displays a different behavior for the same “parseContent()” method.

However, building that new class will be covered in the next section. So click on the link below and read the next few lines.

{mospagebreak title=Displaying HTML paragraphs using an object-oriented approach}

As I explained in the preceding section, to demonstrate that it’s possible to construct polymorph objects by combining the functionality of interfaces and abstract class, I"m going to derive a new child class from the parent “HtmlElement,” which also will be an implementer of the “Parser” interface.

Here’s the definition of the new subclass, whose function is to render HTML paragraphs:

// define Paragraph class (subclass of HtmlElement class)

class Paragraph extends HtmlElement

{

public function parseContent()

{

if ($this->content !== ”)

{

$this->content = str_replace(array(‘</p>’,'</p>)’), "", $this->content);

 

}

return $this;

}

// render paragraph element

public function render()

{

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

 

}

}

Didn’t I tell you that building a polymorph class by using interfaces and abstract classes was a straightforward process? Well, if you pay close attention to the above “Paragraph” class, then you’ll realize that I was right.

Obviously, aside from inheriting all of the methods defined by its corresponding parent, this child class gives concrete implementation to the “parseContent()” method declared within the “Parser” interface. Nonetheless, this time the method will remove any “<p></p>” tags included in the contents of the HTML paragraphs being constructed.

Do you see how simple it is to make two classes that belong to the same family and implement the same interface behave entirely differently? I guess you do. However, to dissipate any doubts that you might have on this topic, in the last segment of this tutorial I’m going to set up an example that will show how to work with the previous “Paragraph” class.

Therefore, to see how this final example will be developed, read the following section. I’ll be there, waiting for you.

{mospagebreak title=The polymorph class in action}

Undeniably, the best way to understand how the “Paragraph” polymorph class developed in the previous segment can be utilized in a useful fashion is by means of a concrete example. Thus, in the following lines I coded a script that creates an instance of this class for constructing a trivial HTML paragraph: 

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

Due to the simplicity of the above code sample, I’m not going to waste your time (and mine) with boring explanations regarding its functioning. It’s valid to note here, though, that I deliberately passed a paragraph to the “setContent()” method, which is automatically stripped off, in response to the call to “parseContent().”

And with this example, I’m wrapping up this penultimate episode of the series. As always, you’re free to tweak the source code of the classes shown here, so you can improve your skills in building polymorph objects with PHP 5.

Final thoughts

In this penultimate part of the series, I demonstrated how easy it is to build in PHP polymorph objects that merge the functionality of abstract classes and the structure of interfaces. As you saw for yourself, the whole creation process was very simple, so in theory you shouldn’t have major problems grasping its underlying logic.

In the final chapter of this series, I’m going to show you how to put the previous “Div” and “Paragraph” polymorph classes to work side by side, so you can clearly see how they behave differently when used within the same script.

Don’t miss the last article!

Google+ Comments

Google+ Comments