Creating a Subclass for Building Polymorphs in PHP

Welcome to the fourth installment of an article series on building polymorphs in PHP. Made up of seven tutorials, this series attempts to teach you through numerous, comprehensive code samples how to create polymorph objects. You’ll see how to do it using interfaces, then abstract classes, and finally a combination of both.

Now that you know what to expect from this set of articles, it’s time to summarize the topics covered in the last one. In that part of the series I started developing a basic example to demonstrate how to build a couple of polymorph classes that inherited most of their functionality from a base abstract class.

To extend this explanation, the aforementioned base class encapsulated most of the logic required for creating generic HTML elements. This made it very easy to derive a subclass from it and provide this child entity with the ability to render basic HTML divs.

Of course, it’s also fair to note that this example in its current state doesn’t clearly show how the class responsible for displaying divs on screen really behaves as a polymorph structure. However, if another child class is spawned from the corresponding parent, and it does display a different behavior when one of its methods gets called, then it’d be easy to demonstrate the polymorph nature of these classes, right?

Well, that’s exactly what I’m going to do in the next few lines For this concrete example, the brand new subclass that I plan to build next will be tasked with creating some HTML paragraphs.

Now, to learn how this will be done, click on the link below and start reading!

{mospagebreak title=Review: building polymorph objects by using abstract classes}

As I stated in the introduction, my plan for this tutorial consists of deriving a whole new child class from the parent that builds generic HTML elements, and making it capable of displaying paragraphs. So, it’d be useful to recall how the parent class was originally defined, along with the subclass that constructs divs.

Please take a look at the signature of the abstract “HtmlElement” parent class, which was developed in the following way:

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 definition of the above “HtmlElement” abstract class speaks for itself. It declares and implements some simple methods for constructing generic HTML elements. Despite the trivial source code of this particular class, it must be noted that its “render()” method has no concrete implementation.

You may be wondering what’s the point is in doing this. Well, the answer is really simple: if several subclasses provide a refined implementation for the method, then it’s possible to create a set of children that build all sorts of HTML elements. It’s simple and efficient.

The following “Div” class adds to the “render()” method the logic required for creating divs. Here it is:

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

 

}

}

Done. Now, there’s a subclass that’s capable of rendering divs on the browser. Don’t believe me? Then give the script below a try and see the output that it produces:

// 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 you can see, once an instance of the “Div” class has been created, it’s extremely easy to display a div on the browser, thanks to its chainable API.

The most important detail here, though, is that this class displays a determined behavior when its “render()” method is invoked. But what happens if I derive another subclass from the parent “HtmlElement” and make the same method capable of rendering paragraphs?

That would be pretty interesting, since there would be two classes that belong to the same family but behave differently. Hey, that’s exactly the characteristic that distinguishes polymorphs from regular objects!

Naturally, to demonstrate this concept it’s necessary to create the subclass that will build HTML paragraphs. This process will be covered in depth in the following section, so click on the link below and keep reading.

{mospagebreak title=Building another polymorph subclass}

As I explained in the section that you just read, to demonstrate that many of the subclasses derived from the parent “HtmlElement” can be considered true polymorph entities, it’s necessary to build a class that behaves radically different when its “render()” method gets called.

With that requirement in mind, below I included the definition of this brand new subclass. It’s charged with building HTML paragraphs. Look at it, please:

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

 

}

}

Were you expecting to be confronted with a complex and lengthy class? Well, fortunately for you and me this isn’t the case here. The task that the “Paragraph” class performs is constructing HTML paragraphs via its inherited “render()” method.

Now that this new subclass has been completely defined, it should be clear for you to see its polymorph nature, particularly when compared with its sister “Div.” These two child classes are of the same “HtmlElement” type, but each of them acts radically different when rendering a specific HTML element.

At this point, you’ve hopefully grasped the logic that stands behind building polymorph objects using an abstract class in PHP 5. But, there’s still one thing that remains undone — developing a script that shows how to use the previous “Paragraph” class.

That script will be built in the last part of this tutorial. Therefore, click on the link that appears below and read the next few lines.

{mospagebreak title=The functionality of a polymorph object}

It’s quite possible that your concept on building polymorph objects via abstract classes is now spot on. However, for the sake of completeness, I’m going to develop a trivial script that demonstrates the actual functionality of the “Paragraph” subclass that you learned in the previous segment.

Having said that, here’s how this final script looks:

// 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 to code but pretty illustrative, right? Definitely, there’s not much that can be said about the way that the “Paragraph” class works when using an instance of it, except for its behavior in response to a call to its “render()” method.

If you compare this basic example with the one that showed how to use the “Div” class, then you’ll realize why these two subclasses are considered polymorphs. Of course, it’s possible to create more subclasses that implement the “render()” method differently, but this will be left as homework for you, if you’re feeling bored and look for something really fun.

Final thoughts

That’s all for now. In this fourth chapter of the series, you learned how to take advantage of Polymorphism in PHP 5 by using a single abstract class and a couple of subclasses. As you saw for yourself, this process was indeed a no-brainer, so you shouldn’t have major problems understanding its driving logic.

Now, go back for a moment in time and recall the concepts deployed in the two first articles of the series. Remember that I discussed the construction of polymorph objects by using interfaces? That was a good experience, but in the real world, it is often necessary to build polymorph classes that inherit methods from both interfaces and parent classes simultaneously. This is a powerful approach.

Therefore, in the next article I’m going to show you how to apply this handy method with the pair of HTML element classes that you saw previously. Don’t miss the upcoming part!

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

chat sex hikayeleri Ensest hikaye