Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Practical PHP Patterns: Transform View

DZone 's Guide to

Practical PHP Patterns: Transform View

· Web Dev Zone ·
Free Resource

The Transform View pattern involves a view mechanism that processes data structures one element at the time, and transforms them into an end-user representation like HTML.
The Transform View usually takes the shape of a view class (or function) with these characterizing traits:

  • its input is domain model data structure, or an infrastructure one that contains domain elements like a Collection class or an array.
  • Its output is a presentational data structure like an HTML page or a page block. Recently, also XML or JSON have become output formats.

In fact, the simplest example of a natively available Transform View in PHP is the function json_encode(): it takes an array of data as its argument, and boils it down to a JSON string. It is not capable of navigating a more complex object graph to render it, but the intent of this pattern is intact.

Implementation

The Transform View can act over multiple objects or a single one. Its main difference with a Template View is the mechanism for expressing the production of the response: the first is a series of operation to apply to domain elements, the second is the representation itself with several hooks where dynamic content is inserted.

Concretely, we can think of the Template View as a PHP script, maybe driven by a generic class that renders it when a method is called; the Transform View is instead composed of programmatic (code): it can be a class or method.

Since patterns may be rendered more complex at will, you can introduce implementations that use XSLT to generates HTML or other representations from an XML one (with the XSL extension); but you still have to get the original XML one, maybe by introspection of the domain structures.

XSL essentially it is a way to define transformations declaratively, mixing the two approaches and producing a portable description of the transformation which data undergo; many times you're better off by simply defining your transformation in code and cover (or drive) it with tests.

A trade-off is that you can always use this pattern only for some parts of the page (when the output is oriented to humans and not to machines), as in the Two Step View pattern which we'll see in the next article. These particular Transform Views are a subset of View Helpers, which take domain objects as their input.

Data access

Infrastructure classes are usually navigable via their own Api, which is very rich. Domain classes instead are focused on modelling and information hiding instead of navigability, and this may raise an issue for displaying them through every kind of view. When a set of properties is exposed by a domain object directly or via accessors, we have two choices in building a Transform View:

  • the object can be introspected dynamically, by using reflection or other metadata (e.g. annotations) to list public properties or getters.
  • more specific Transform Views can be written which are designed only for usage on a particular class. They will present a strong coupling with the original domain data structure but also a finer control on the presentation layer.

Advantages

An obvious advantage of this pattern is code reuse when the implementation is generic enough to be valid for more than one class.

A more subtle advantage may be the homogeneity of the different Transform Views objects. For example you may end up swapping different Transform Views or chaining them, or relying on polymorphism to select the right rendering for a use case. In general, promoting the View mechanism to an object yields the advantages of object-orientation (inheritance, polymorphism, encapsulation), and these pros are more easily perceived with a logic-intensive approach like a Transform View.

Disadvantages

The issues of this pattern come up with markup-intensive pages which contain a lot of semi-static HTML code, or of another presentational format. Such pages are often much easier to produce with a Template View when dynamic bindings are submerged. Even XML sometimes it's easier to print out tag by tag with Template View instead of managing a DOM implementation.

Examples

The sample code of this article regards using reflection to gather getters of a domain object and display it. Of course it is not a complete implementation (it does not cover relationships), but in its limited scope is quite useful.

As always, you may prefer more specific incarnation of the pattern, but they will have to be kept in sync with the related domain model and constitute a larger code footprint. However, they will give you more freedom to tune the result in specific cases.

<?php
/**
* A classic entity class, part of the Domain Model.
*/
class User
{
private $_name;
private $_city = '';

public function __construct($name)
{
$this->_name = $name;
}

public function getName()
{
return $this->_name;
}

public function setCity($city)
{
$this->_city = $city;
}

public function getCity()
{
return $this->_city;
}
}

class TransformView
{
/**
* Iterates through getters and calls them to display $entity.
* @param object $entity
* @return string
*/
public function display($entity)
{
$result = "<table>\n";
$rc = new ReflectionClass(get_class($entity));
foreach ($rc->getMethods() as $method) {
$methodName = $method->getName();
if (strstr($methodName, 'get') == $methodName) {
$field = str_replace('get', '', $methodName);
$result .= "<tr>\n";
$result .= "<td>{$field}</td>\n";
$result .= "<td>" . $entity->$methodName() . "</td>\n";
$result .= "</tr>\n";
}
}
$result .= "</table>\n";
return $result;
}
}

$user = new User('Giorgio');
$user->setCity('Como');
$view = new TransformView();
echo $view->display($user);
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}