DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Inheritance in PHP: A Simple Guide With Examples
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Laravel for Beginners: An Overview of the PHP Framework
  • Is PHP Still the Best Language in 2024?

Trending

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Measuring the Impact of AI on Software Engineering Productivity
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Patterns: Transform View

Practical PHP Patterns: Transform View

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Jul. 27, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
4.3K Views

Join the DZone community and get the full member experience.

Join For Free

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);
PHP

Opinions expressed by DZone contributors are their own.

Related

  • Inheritance in PHP: A Simple Guide With Examples
  • The Blue Elephant in the Room: Why PHP Should Not Be Ignored Now or Ever
  • Laravel for Beginners: An Overview of the PHP Framework
  • Is PHP Still the Best Language in 2024?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!