HomePHP PHP: View Object Collections and the Composite View Design
PHP: View Object Collections and the Composite View Design
In this second part of a series, I demonstrate how to create a concrete composite view class, capable of rendering single and multiple view templates via the same “render()” method. The definition of this brand new class not only shows the logic that drives the Composite View pattern, but reveals how the pattern takes advantage of the benefits offered by Composition.
As its name suggests, the Composite View design pattern is a subtle variation of the “standard” Composite, which permits you to manipulate indiscriminately a single view object and a collection of them through the same interface. As with many other popular patterns, the implementation of Composite View may vary across different programming languages and applications; when used specifically in PHP, however, it provides a remarkable flexibility for handling (X)HTML templates in all sorts of clever ways, including the creation of nested views and master web page layouts.
Even though at first glance the application of the Composite View pattern in PHP appears to be difficult, suitable only for experienced developers, the truth is its implementation is a fairly simple task that can be mastered with only an average background in the object-oriented programming paradigm.
To demonstrate the truth of my words, in the introductory part of this series I built an abstract parent class for defining the generic structure and behavior of view objects. What’s more, the current functionality of this abstract parent allows you to dynamically assign properties to these objects, and individually render their associated templates via a simple method called, not surprisingly, “render().”
Having at our disposal a class that does all of this with a single view object is fine. But it would be even better to create a class capable of rendering single and multiple view templates equally through the same “render()” method. After all, that is exactly the purpose of the Composite View pattern, isn’t it?
To fit this requirement, in this second tutorial of the series I’m going to define such a class, which will be a refined implementation of the abstract parent created previously.
Are you ready to learn the full details of this refinement process? Then jump forward and begin reading!