Home arrow PHP arrow Page 2 - PHP Creating HTML Widgets

Adding behavior to the Div class with a method for nesting Div objects - PHP

In this third part of a series I develop another sample class, which will use the Object Value design pattern to create immutable HTML div objects in a few easy steps. The pattern's implementation in this case will be a bit more interesting than usual -- it will use the PHP built-in type hinting feature to define a method that returns a new div object to client code, while keeping the immutability of the originating object intact.

TABLE OF CONTENTS:
  1. PHP Creating HTML Widgets
  2. Adding behavior to the Div class with a method for nesting Div objects
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
November 09, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

In reality, giving the earlier “Div” class the ability to nest div elements is a pretty straightforward process. Basically, the procedure is reduced to implementing a discrete method, like the one shown below, which performs this task without altering the class’ immutability. Here it is:

// nest two div elements inside another one (returns a new Div object)
public function nest(Div $div)
{
    $content = $this->render() . $div->render();
    return new Div($content);
}       

Despite the short definition of the “nest()” method, the way it’s been implemented deserves a closer look. In this case, you should notice that the method employs the functionality of type hinting to inject a div object into the class’ internals, which is used later on to generate a new object, whose content is a combination of the originating object’s content and of the injected one. This simple process allows you to easily create nested divs without having to break the immutability of the involved objects.

And now that you've surely grasped the logic behind the previous “nest()” method, here’s how the corresponding “Div” class looks after appending the method to its source existing code:   

(Div.php)

<?php

final class Div implements HtmlWidgetInterface
{
     private $_content;
    
     // constructor
     public function __construct($content)
     {
         if (!is_string($content) || empty($content)) {
             throw new HtmlWidgetException('The content assigned to the div element must be a non-empty string.');
         }
        
         $this->_content = $content;
     }
    
     // get the the content of the div element
     public function getContent()
     {
         return $this->_content;
     }
    
     // render the div element
     public function render()
     {
         return '<div>' . $this->_content . '</div>';
     }
    
     // nest two div elements inside another one (returns a new Div object)
     public function nest(Div $div)
     {
         $content = $this->render() . $div->render();
         return new Div($content);
     }       
}

As you can see, I managed to build a basic class capable of spawning immutable div objects, which also makes use of composition (and therefore dependency injection) to create nested div elements in a snap. But, is the class really as functional as it seems at first sight? Well, the only way to dissipate your doubts is by setting up an example that puts the class to work.

That’s exactly what I’ll be doing below, so keep reading. 
 
Setting up a final example

In line with the concepts deployed above, here’s an example that shows how to use the previous “Div” class to spawn first a couple of immutable div objects, and then a third one, which is simply a combination of the others. Take a look the corresponding code sample:

<?php

// example of immutable value objects using the Div class

require_once 'HtmlWidgetInterface.php';
require_once 'Div.php';

// create the first two div objects
$div1 = new Div('This is the content of the first div.');
$div2 = new Div('This is the content for the second div.');

// nest the two previous divs and create a new one
$div3 = $div1->nest($div2);
// render the new div
echo $div3->render();

/* displays the following
<div><div>This is the content of the first div.</div><div>This is the content for the second div.</div></div>
*/

There you have it. As you can see from the above example, once the first two div objects have been properly created, generating a third one is a breeze thanks to the functionality provided by the “nest()” method discussed previously. Finally, the contents of this last object are echoed to the screen via its “render()” method, a process that effectively demonstrates the immutability of the participant objects.

Armed with the code samples developed so far, plus a bit of willpower, you should be able to create your own immutable classes, an experience that will help you acquire a better understanding of how to implement the Value Object pattern in PHP. So, what are you waiting for? Go for it!

Final thoughts

That’s all for the moment. In this third part of the series I went through the development of another sample class, which took advantage of the functionality provided by the Object Value design pattern to create immutable HTML div objects in a few easy steps. As you just saw, the implementation of the pattern in this case was a bit more interesting than usual, as it used the PHP built-in type hinting feature to define a method that returned a new div object to client code, while keeping the immutability of the originating object intact.

Again, this puts in evidence a key concept that was discussed in depth in previous tutorials: any method that attempts to alter the values assigned to the fields of an immutable object will result in the creation of another object, regardless of the simplicity (or complexity) of the method in question. Thus, make sure to meet this requirement when coding your own immutable classes.

Now, moving on, in the last part of the series I’ll be defining another example immutable class, which in this case will be tasked with encrypting user-supplied passwords. So, my little piece of advice is simple and straightforward: don’t miss the last installment! 



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: