Having built an abstract parent class that encapsulates most of the functionality required to build generic HTML objects, the next step is to derive a couple of subclasses, which in this particular case will be charged with rendering some basic paragraphs and divs. Fortunately, this process is reduced to overriding the “render()” method defined by the corresponding parent, as shown below: (Div.php) <?php class Div extends HtmlElement { public function render() { return '<div class="' . $this->getClass() . '" id="' . $this->getId() . '">'. $this->getContent() . '</div>'; } } As the previous code fragment illustrates, building a class that renders div elements is indeed a breeze. But wait a minute! A I just mentioned, it’s necessary to define yet another class that generates the markup of a paragraph, right? Well, the one coded below does exactly that. Check it out: (Paragraph.php) <?php class Paragraph extends HtmlElement { public function render() { return '<p class="' . $this->getClass() . '" id="' . $this->getId() . '">'. $this->getContent() . '</p>'; } } Considering that the logic implemented by the above “Paragraph” class is nearly identical to its cousin “Div,” I’m not going to waste your valuable time explaining how it works. Instead, you should focus your attention on the following script, which uses these classes to display a div and a paragraph on the browser: // include the source classes require_once 'Div.php'; require_once 'Paragraph.php'; // create an instance of the Div class $div = new Div; // render and display a div echo $div->setClass('divclass') ->setId('divid') ->setContent('This is the content of the div.') ->render(); // create an instance of the Paragraph class $par = new Paragraph; // render and display a paragraph echo $par->setClass('parclass') ->setId('parid') ->setContent('This is the content of the paragraph.') ->render(); Mission accomplished. At this stage, it’s clear to see that the previous “Div” and “Paragraph” classes do decent work rendering these HTML elements on screen. In the above example, they’ve been used as standalone structures, which is all well and good. Nevertheless, it’d be really useful to demonstrate how to build these elements by using the factory classes defined before, so you can see how versatile they can be, thanks to the functionality provided by LSB. That will be covered in the next part. Final thoughts In this penultimate installment of the series, I went through the definition of some sample classes, which were responsible for creating some block-level (X)HTML objects such as simple divs and paragraphs. With these classes already up and running, the scenario is finally ready to test the previous factories and see if they’re actually as functional as they look at first sight. Considering that the full details of this process will be discussed in the upcoming article, here’s my little piece of advice: don’t miss the last tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|