Combining Interfaces and Abstract Classes to Build Polymorphs in PHP

In this fifth part of a seven-part series on building polymorphs in PHP 5, you will learn how to build a polymorph object by combining an abstract class and a simple interface. As you’ll see, this object will be used for constructing basic HTML divs.

Without a doubt, understanding how to build polymorph objects in PHP 5 can be of great help when developing object-oriented web applications. this is especially true if you want to make use of the big pillars of software engineering in a truly efficient way.

In addition, it’s quite possible that you, as a self-taught PHP developer, have already implemented Polymorphism in your own web-based programs without even knowing it. This is good; however, you should learn the theoretical concepts that surround the application of this key programming technique sooner or later in your career. This is especially true if your goal is to become a professional programmer.

Fortunately, in the case of PHP 5, Polymorphism can be achieved in a pretty straightforward fashion, even by those who have only an intermediate background in the object-oriented paradigm and the use of interfaces.

Naturally, if you’ve already read all of the articles that precede this one, then hopefully at this point you’ll have a solid background in how to build polymorph objects using interfaces and through abstract classes. In those tutorials I explained with a decent variety of code samples how to use Polymorphism for constructing objects that rendered some basic HTML elements, including divs and paragraphs.

However, one thing that must be noticed with reference to these examples is that they implemented Polymorphism through either interfaces or abstract classes, but never by utilizing both approaches at the same time. So, can this be done successfully? Fortunately, the answer is yes! Moreover, the process is so easy to accomplish that it’s reduced to creating some subclasses from a base class, while making these children implementers of a certain interface. This is it.

In the next few lines I’m going to demonstrate how to work simultaneously with interfaces and abstract classes to implement Polymorphism in PHP 5.

Don’t waste more time and begin reading right now!

{mospagebreak title=Achieving Polymorphism via abstract classes}

As I explained in the introduction, PHP 5 makes it really easy to implement Polymorphism by combining the functionality of abstract classes and interfaces. But before I dive more deeply into the details of how to accomplish this, I’d like to spend a few moments reintroducing the example application developed in the previous article of the series. It showed how to build a couple of polymorph objects by way of a simple abstract class.

That being clarified, here’s the definition of that abstract class, which encapsulates most of the functionality required for creating HTML elements. Look at it, please:

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 shown before, the signature of the “HtmlElement” abstract class includes nothing special. It simply defines some basic methods for assigning “id” and “class” attributes to the HTML element being created, as well as for setting its content.

Of course, the class’s “render()” method has no concrete implementation, since this process should be delegated entirely to the eventual subclasses. Below you’ll find the signatures of two child classes that use the method for displaying paragraphs and a div, respectively, on screen. Here they are:

// 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>';

 

}

}

 

// define Paragraph class (subclass of HtmlElement class)

class Paragraph extends HtmlElement

{

// render paragraph element

public function render()

{

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

 

}

}

As I stated previously, the pair of subclasses shown above add concrete logic to the inherited “render()” method for constructing HTML divs and paragraphs respectively. This demonstrates that two classes that are of the same type can behave differently when the same method is called.

If you have any doubts about the polymorph nature of these classes, then take a look at the following script, which should help to dissipate them quickly:

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

 

// 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(‘parid’)->setClass(‘parclass’)->setContent(‘This is the new content for the paragraph.’)->render();

Simple and illustrative. From the previous code fragment it’s clear to see how easy it is to build polymorph objects by using an abstract class. This is by far the most common approach that can be used for implementing Polymorphism in PHP 5. As I discussed in a previous part of this series, it’s also possible to use interfaces, even though this approach doesn’t fully exploit the benefits of Inheritance, for obvious reasons.

Nonetheless, as this article’s title suggests, it’s feasible to construct polymorph objects by combining abstract classes and interfaces with relative ease. So, in the next section I’m going to demonstrate how to do this with some of the sample classes shown previously.

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

{mospagebreak title=Defining a simple interface and an abstract class}

Since my plan here consists of demonstrating how to construct polymorph objects by combining interfaces and abstract classes together, I’m going to reuse the “HtmlElement” class that you saw in the previous segment, along with a brand new interface called “Parser.” Later on, these entities will be used again for constructing more complex HTML elements. 

Having explained my goal, it’s example time. So, here’s the trivial definition of the “Parser” interface, along with the corresponding “HtmlElement” class:

 

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

}

Since the purpose of the “Parser()” interface is to provide structure to any HTML element, and the abstract class adds logic to that element, there’s nothing special to note with reference to the previous code fragment. However, it’s valid to say that if I derive a subclass from the base “HtmlElement” that also implements the “Parser()” interface, this child would be inheriting both structure and logic, right?

This could be useful if you want to specify different behaviors for diverse HTML element objects when their inherited “parseContent()” method gets invoked.

Let me clarify this concept, so you can grasp it more easily: the “Div” class built in the previous section could implement the “parseContent()” method to replace certain incorrect tags, such as “<html> and “<body”>, with “<div>” tags when assigning its contents. Its sister “Paragraph” could do something similar, but in that case it’d simply remove nested paragraphs.

Well, if this explanation still sounds a bit confusing to you, fear not; in the last section of this tutorial I’m going to show you how to redefine the previous “Div” class so it can engage in the aforementioned polymorph behavior.

Now, read the upcoming segment. We’re almost finished!

{mospagebreak title=Building an improved polymorph class}

In the earlier section I defined a simple interface in conjunction with the “HtmlElement” abstract class, so next I’ll build a subclass that implements the interface.

Want to see how this can be accomplished in a single step? Look at the following code sample, which redefines the “Div” class that you saw before:

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

 

}

}

By examining the definition of the improved “Div” class, you can see how easy it is to build polymorph objects that inherit structure and functionality from an interface and an abstract class. Please, notice how this concrete class implements the inherited “parseContent()” method to replace some invalid tags with divs, thus basically sanitizing its contents.

Now that you’ve grasped the driving logic of the previous class, it’s time to see how it can be used for displaying a single div on the browser. The following script shows how to do that:

 

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

->parseContent()

->render();

Here you have it. With this basic example I showed that constructing polymorph classes that inherit methods from an abstract class and one or more interfaces is indeed a straightforward process.

As usual, feel free to tweak all of the code samples included in this tutorial, so you can sharpen your Polymorphism skills in PHP 5.

Final thoughts

This is it for the moment. Over the course of this fifth chapter of the series, you learned how to build a polymorph object in PHP 5 by combining an abstract class and a simple interface, which was useful for constructing basic HTML divs.

In the next tutorial I’m going to show you how to construct a polymorph class using the previous approach, but this time the class will be responsible for rendering HTML paragraphs.

Don’t miss the upcoming article!

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

chat sex hikayeleri Ensest hikaye