PHP Creating HTML Widgets

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.

Even though at first glance it looks like an obscure and esoteric principle not worth analyzing in detail, the Value Object design pattern is a simple paradigm that permits you to generate, that is, objects whose equality is measured by the values assigned to their fields and not on a unique identity.

Unlike other programming languages, PHP doesn’t package by default a lot of native value objects, with the exception of the ones that can be spawned from its built-in ArrayObject and DateTime classes. The good news, though, is that creating them is a extremely easy process that you can tackle even if you have only an average background in the object-oriented approach. To demonstrate how simple it is to build immutable value objects using a custom class, in previous parts of this series I went through the development of a basic one, whose primary responsibility was modeling immutable URL objects.

By far, the most relevant facet of this construction process was the implementation of a method within the class, which was tasked with appending additional arguments to its existing query string. Considering the immutable nature of the class, the method acted like a simple factory which returned new URL objects to client code, in this way preserving the values assigned initially to the class’ fields.

As you may have already realized, the creation of immutable value objects isn’t limited to modeling well-formed URLs, as the process can easily be extended to other types of objects as well. So, since my goal here is to demonstrate the functionality of the Value Object pattern from a practical point of view, in this penultimate tutorial of the series I’m going to define another basic class, which will be charged with building a few immutable HTML widgets, and more specifically div elements.

Are you ready to learn the details of this process? Then keep reading.

Getting started building an immutable HTML widget class

As I said in the introduction, my purpose in this tutorial is to build a class capable of building immutable div objects. In keeping with this, I’ll start by defining a contract for creating generic HTML widgets. Obviously, this can be easily achieved with an interface, so below is the definition of the one that I plan to use. Look at it, please:

(HtmlWidgetInterface.php)

<?php

interface HtmlWidgetInterface
{         
    public function render(); 
}

Well, to be frank there’s no much that can be said about the above “HtmlWidgetInterface.” It declares a method called “render(),” which naturally must be provided with a concrete definition by all the classes implementing the interface in question.

With this simple contract already set, the next step is to create a class responsible for spawning the immutable div objects just mentioned. This class is not surprisingly called “Div,” and its source code is shown below:
  
(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 content of the div element
     public function getContent()
     {
         return $this->_content;
     }
    
     // render the div element
     public function render()
     {
         return ‘<div>’ . $this->_content . ‘</div>';
     }
}

 

(HtmlWidgetException.php)

<?php

class HtmlWidgetException extends Exception{}

That was simple to code and read, wasn’t it? Similar to the examples developed in prior parts of this series, the brand new “Div” class doesn’t expose any setter methods to client code, in this way making it possible to create immutable div objects. In addition, the class concretely implements the “render()” method declared by the pertinent “HtmlWidgetInterface” interface, thus fulfilling the contract as expected.

So far, so good. At this point, if you give the “Div” class a try, it should work decently well, as each call to its “render()” method would effectively render a basic HTML div per object being created. However, in its current incarnation the behavior of the class is actually very limited; it’d be desirable to provide it with an extended functionality. In line with this idea, in the next section I’m going to add to the class a new method, which will be capable of rendering nested divs.

If you’re anything like me, at this moment you’re wondering how this will be done without affecting the class’ immutability, right? Well, to find out the answer to your question, you’ll have to click on the link below and read the following segment. 

{mospagebreak title=Adding behavior to the Div class with a method for nesting Div objects}

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! 

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort