HomePHP Rendering HTML Paragraphs with Polymorphs in PHP 5
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!