PHP Object Oriented Programming using LSP

This second look at the Liskov Substitution Principle aims to teach you how to develop better, more powerful PHP applications.

Being one of the building blocks of the SOLID principles, the Liskov Substitution Principle is a fundamental pillar of Object Oriented Design (OOD), whose formulation is aimed at solving the issues associated with poorly-designed hierarchies of classes. Even though its formal definition is somewhat hard to grasp, in practical terms it states that methods defined in a base class (or interface) and their derivatives must have the same signature, preconditions should be weakened in the formers, and post-conditions should be strengthened. In addition, if methods in subtypes throw exceptions, they should be of the same type as the ones thrown by the parent abstraction.

It might take a while to understand the logic that stands behind LSP; possibly the most challenging facet is to demonstrate the consequences when its infringement occurs in the real world. So, in an attempt to cover the principle from this standpoint, in the introductory part of this tutorial, I showed how the improper implementation of a class hierarchy in a composite view rendering module can cause unexpected exceptions when one of the module’s subtypes (in this case a child class tasked with rendering partial views) unintentionally strengthened the aforementioned preconditions.

If you missed the first installment or would like a refresher, you can find the article here:

http://www.devshed.com/c/a/PHP/PHP-Liskov-Substitution-Principle/

Defining a Few New Segregated Contracts

As I explained in the introductory chapter, my biggest mistake was to place (from the very beginning) the entire composite view module on the wrong abstraction. While any composite view could be easily consumed by my trivial layout builder, things were radically different when the builder was fed with a partial, as the process always threw an unexpected exception. This was a clear sign of code smell and a flagrant violation of LSP, so I decided to switch to a few granular and disparate contracts, instead of using the one declared by a single abstract class.     

With that idea in mind, the first thing that I needed to do was to define the aforementioned contracts, something that in this particular case was achieved through some segregated interfaces, which looked like this:

(App/Common/Aggregable.php) <?php namespace AppCommon; interface Aggregable
{
    public function add($element, $key = null);     public function addMultiple(array $elements);
}   (App/Common/Removable.php) <?php namespace AppCommon; interface Removable
{
    public function remove($element);
}   (App/Common/Renderable.php) <?php namespace AppCommon; interface Renderable
{
    public function render();
}

Although the methods declared by the above interfaces were pretty self-explanatory, they solved my main issue: simply put, they gave me the liberty to create composite and partial views without having to rely on the same abstract parent. And – most importantly – without breaking up its contract in the subtypes.

Moreover, if I ever wanted to create a composite view class, the process would be reduced to spawning an implementer of the pertaining interfaces and nothing else. On the other hand, a partial would implement only the “renderable()” interface, as it wouldn’t need the functionality required for adding and removing other views.

With these highly-granular interfaces already set, I had a much clearer idea of how to implement an improved version of the composite view module. There was, however, an additional step that needed to be taken to get things working as intended: it was necessary to encapsulate common functionality shared by the composite views and partials in one single place. Thus, I thought to myself that the best way to accomplish this would be by creating an abstract view class; so after thinking for a while I ended up building a brand new base class along with a couple of derivatives. 

To see how these classes were built, move forward and keep reading.

Taking the Next Step: Refactoring the Composite View Rendering Layer

The most effective way to create an LSP-compliant hierarchy of composite and partial views was to rest the whole structure on a new abstract parent, whose contract and functionality were shared by both types of views.

With that concept in mind, I came up with an improved base class, whose implementation was as follows:

(App/View/AbstractView.php) <?php namespace AppView; abstract class AbstractView
{
    protected $_values = array();
    protected $_templateDirectory = 'Templates';
    protected $_templateFile = 'default_template.php';     /**
     * Constructor
     */
    public function __construct(array $templateOptions = array())
    {
        // Set the view template directory
        if (isset($templateOptions['templateDirectory'])) {
            $this->setTemplateDirectory($templateOptions['templateDirectory']);
        }
        // Set the view template file
        if (isset($templateOptions['templateFile'])) {
            $this->setTemplateFile($templateOptions['templateFile']);
        }
    }     /**
     * Set the view template directory
     */
    public function setTemplateDirectory($templateDirectory)
    {
        if (!is_dir($templateDirectory)) {
            throw new InvalidArgumentException('The template directory ' . $templateDirectory . ' is invalid.');
        }
        $this->_templateDirectory = $templateDirectory;   
    }     /**
     * Get the template directory
     */
    public function getTemplateDirectory()
    {
        return $this->_templateDirectory;
    }
     
    /**
     * Set the view template file
     */
    public function setTemplateFile($templateFile)
    {
        $templateFile = $this->_templateDirectory . DIRECTORY_SEPARATOR . $templateFile;
        if (!file_exists($templateFile) || !is_readable($templateFile)) {
            throw new InvalidArgumentException('The template file ' . $templateFile . ' is invalid.');
        }
        $this->_templateFile = $templateFile;
    }
     
    /**
     * Get the view template file
     */
    public function getTemplateFile()
    {
        return $this->_templateFile;
    }     /**
     * Assign a value to the specified field of the view via the corresponding mutator (if it exists);
     * otherwise, assign the value directly to the '$_values' protected array
     */
    public function __set($name, $value)
    {
        $mutator = 'set' . ucfirst(strtolower($name));
        if (method_exists($this, $mutator) && is_callable(array($this, $mutator))) {
            $this->$mutator($value);
        }
        else {
            $this->_values[$name] = $value;
        }
    }     /**
     * Get the value assigned to the specified field of the view via the corresponding getter (if it exists);
     * otherwise, get the value directly from the '$_values' protected array
     */
    public function __get($name)
    {
        $accessor = 'get' . ucfirst(strtolower($name));
        if (method_exists($this, $accessor) && is_callable(array($this, $accessor))) {
            return $this->$accessor;
        }
        if (isset($this->_values[$name])) {
            return $this->_values[$name];
        }
        throw new RunTimeException('The field ' . $name . ' has not been set for this view yet.');
    }     /**
     * Check if the specified field has been assigned to the view
     */
    public function __isset($name)
    {
        return isset($this->_values[$name]);
    }     /**
     * Unset the specified field from the view
     */
    public function __unset($name)
    {
        if (isset($this->_values[$name])) {
            unset($this->_values[$name]);
            return true;
        }
        throw new RunTimeException('The field ' . $name . ' has not been set for this view yet.');
    }     /**
     * Render the template
     */
    protected function _doRender()
    {
        extract($this->_values);
        ob_start();
        include $this->_templateFile;
        return ob_get_clean();
    }     /**
     * Get an associative array with the values assigned to the fields of the view
     */
    public function toArray()
    {
        return $this->_values;
    }
}

Even though the revamped version of this abstract class looks fairly similar to the one implemented in my first take, it does expose a subtle difference worth pointing out: first and foremost, the class no longer declares the abstract “addView()”, “addViews()” and “removeView()” methods, something that allows the sharing of common functionality between composite and partial views and extends their contracts by means of the set of segregated interfaces defined before.

Naturally, the best way to understand how to deal with composites and partials is by showing the couple of subclasses that bring them to life. Thus, here are the refactored incarnations of them:

(App/View/CompositeView.php) <?php namespace AppView;
use AppCommon; class CompositeView extends AbstractView implements CommonAggregable, CommonRemovable, CommonRenderable
{
    protected $_views = array();     /**
     * Add a view
     */
    public function add($view, $key = null)
    {
        if (!$view instanceof AbstractView) {
            throw new InvalidArgumentException('The view to be added must be an instance of AbstractView.');
        }
        if (isset($key)) {
            $this->_views[$key] = $view;
        }
        else {
            $this->_views[] = $view;
        }
        return $this;
    }     /**
     * Add multiple views
     */
    public function addMultiple(array $views)
    {
        foreach ($views as $key => $view) {
            $this->add($view, $key);
        }
        return $this;
    }     /**
     * Remove a view
     */
    public function remove($view)
    {
        if (!$view instanceof AbstractView) {
            throw new InvalidArgumentException('The view to be removed must be an instance of AbstractView.');
        }
        $this->_views = array_filter($this->_views, function ($v) use ($view) {
            return $v !== $view;
        });
        return true;       
    }

    /**
     * Render both the injected views and the current one
     */
    public function render()
    {
        $output = '';
        // render the injected views
        foreach ($this->_views as $_view) {
            $output .= $_view->render();
        }
        // render the current view
        $output .= $this->_doRender();
        return $output;
    }
}   (App/View/PartialView.php) <?php namespace AppView;
use AppCommon; class PartialView extends AbstractView implements CommonRenderable
{
    /**
     * Render the partial view
     */
    public function render()
    {
        return $this->_doRender();
    }
}

Now the implementations of the concrete “CompositeView” and “PartialView” classes look way better, as they only extend the functionality of their abstract parent, in order to handle composite views and partials in a pretty straightforward fashion. In short, this means that all the conditions stated by LSP are nicely met, and - as a consequence -  it’s possible to substitute the base type with subtypes without breaking up a single segment of client code.

But, is this entirely true? Well, as long as the client code consumes instances of “AbstractView”, all should work like a charm. However, what would happen with my humble layout builder, which only accepts composite views to do its business? For obvious reasons, it’s necessary to amend the implementation of the builder too, so that it can work side by side with the revamped version of the “CompositeView” class.

Making a Final Change: Modifying the Implementation of the Layout Builder

As noted in the previous segment, the last change that I needed to introduce into my composite view module was to modify the original implementation of the layout builder. Since this client class initially used its “attachView()” method to take instances of the “AbstractView” class and generate layouts, it was necessary to amend the signature of the method in question, so that it could consume only composite views. 

After making this final change, the definition of the builder was as follows:

(App/Utility/LayoutBuilder.php) <?php namespace AppUtility; use AppCommon,
    AppView; class LayoutBuilder
{
    protected $_views = array();     /**
     * Attach a single view
     */
    public function attachView(CommonAggregable $view, $key = null)
    {
        if (isset($key)) {
            $this->_views[$key] = $view;
        }
        else {
            $this->_views[] = $view;
        }
        return $this;
    }     /**
     * Attach multiple views
     */
    public function attachViews(array $views)
    {
        foreach ($views as $key => $view) {
            $this->attachView($view, $key);
        }
        return $this;
    }     /**
     * Get the attached views
     */
    public function getViews()
    {
        return $this->_views;
    }
   
    /**
     * Build the layout(s)
     */
    public function build()
    {
        foreach ($this->_views as $_view) {
            // create a predefined layout with the attached views
            $_view->addMultiple(array(
                new ViewPartialView(array(
                    'templateFile' => 'header.php'
                )),
                new ViewPartialView(array(
                    'templateFile' => 'body.php'
                )),
                new ViewPartialView(array(
                    'templateFile' => 'footer.php'
                ))
            ));
        }
    }
}

There you have it. At this point, the improved layout builder looked much more effective than the initial one, as the mentioned “attachView()” method was modified to take only composite views. This subtle –yet relevant – detail assured that any object injected into the builder’s internal would implement the “Aggregable” interface (and thereby its “add()” and “addMultiple()” methods) and wouldn’t throw any unexpected exceptions.

Naturally, the best manner to prove that the functionality of the builder was the intended one was by example. Thus, I set up a simple script that put the builder into action (again, the autoloader was omitted for the sake of clarity). Take a look at it:  

<?php use AppUtilityLayoutBuilder as LayoutBuilder,
    AppViewCompositeView as CompositeView; // include the autoloader
require_once 'Autoloader.php';
$autoloader = new Autoloader; // create an instance of the layout builder
$layoutBuilder = new LayoutBuilder; // add a view to the layout builder
$layoutBuilder->attachView(new CompositeView); // generate a layout with the attached view
$layoutBuilder->build();

Mission accomplished. Unlike my first attempt to test the composite view module, which made me confront an unpleasant exception, this time the script ran smoothly and effectively didn’t raise anything weird or unexpected. In summary, I finally managed to create a hierarchy of classes and interfaces that nicely followed the requirements stated by LSP.  

From the previous examples, it’s clear to see the strong relationship that there exists between LSP and design by contract. No matter if contracts are set in interfaces or abstract classes, they shouldn’t never be wildly overridden by subtypes, unless this is absolutely necessary (which is a clear sign of a bad design). So, keep in mind LSP’s statements and your life and your clients’ will be much happier.

Final Thoughts

Over the course of this two-part tutorial, I provided you with a humble introduction to the concepts that surround the application of the Liskov Substitution Principle in PHP, and how its unintentional violation in a real world situation can cause a lot more of headaches than one might think at first. Even when this infringement was, at least in my personal case, relatively harmless in general, the implementation of an effective solution required to refactor several chunks of my original composite view rendering module, not to mention the fact that I had to switch over a different abstraction to make the layout builder to consume only the type of objects that it expected to receive.

Was this a harsh lesson to learn? Undeniable, it was. However, in the end it made me realize that dealing with an incorrect hierarchy of classes where a ISA relationship isn’t entirely fulfilled is an issue that should never be left floating in the limbo.

What’s more, even when PHP exposes a somewhat immature object model (especially when compared to older players like Java and C++), which doesn’t support covariance and contravariance, and where you can implement pre/post conditions in a quite brittle way, the use of LSP has a lot of sense, trust me. Thus, make sure you stick to it in every possible use case, as your OOP applications will rest on a more solid and easier to maintain structure.

See you in the next PHP development tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan