PHP, Zend Framework and Other Crazy Stuff
Archive for April, 2007
Complex Views with the Zend Framework – Part 3: Composite View Pattern
Apr 27th
In the previous two parts of this series of blog posts, I’ve been looking at the task of implementing complex views with the Zend Framework. Part 1 looked at what complex views are, what support for complex views the Zend Framework offers out of the box, and a reference to two design patterns useful in adding further support: View Helper and Composite View. In Part 2, I tackled the View Helper design pattern.
As a brief recap, the View Helper pattern promotes the idea of creating helper classes which allow the View layer of a Model-View-Controller application to directly query the Model layer in a read only fashion – effectively bypassing the Controller layer altogether. In such a way, the pattern offers the option to programmers using the Zend Framework to avoid using the current method of nesting Controller Actions with the Zend_Controller_Action::_forward() method which can be an overly complex approach for parts of a View we know are common to many pages.
In this post, I offer a brief explanation of the Composite View pattern. It’s beyond its scope to show an implementation using the Zend Framework though that’s what I’m building up to accomplish in a later blog entry
.
If you haven’t already guessed, the Composite View pattern is related to the Composite Pattern as defined by the Group of Four (GoF). If you’re not familiar with the Composite Pattern, an excellent PHP article for it was published on Zend Devzone and is worth reading.
Here’s a UML diagram of the class relationship although we do things a little different below
.

In brief the related Composite View pattern organises View objects into a nested tree structure, in which both parents and children implement some common interface (let’s say render() for now). You can think of each View representing a single element of the overall page, with parents representing sections of the overall page which may contain other component elements. The essential characteristic, inherited from the Composite Pattern, is that the common render() method can be called from the root View, and this method call propagates across all nested objects in the tree until the output from all child Views is finally aggregated into the overall page we intend sending to the browser.
With this description we can make a few assumptions regarding the Zend Framework. The main one being we will need multiple instances of Zend_View to pull it off (as distinct from multiple Controllers). Also all this talk of objects hasn’t explained how the nesting is controlled. We’ll handle the second now, and come back to the Zend_View multiplicity after.
There are two methods of handling nesting of View objects. The first follows a purely object based scheme, where objects are nested and combined at runtime. The second passes control over nesting to our friends – the templates. The template method basically involves adding a function (think of the Composite Pattern’s interface for “composites”) to include another template. Here we’ll call it “attach”, though it could be anything you prefer. We’ll look at this approach below since it’s the simplest one to follow if you’re familiar with Zend_View templates. In addition, the template approach is probably the easiest for programmers and designers to handle since it allows the View layout to be put in place around all these composite View includes.
Now, we may appear to have come full circle here – this sounds suspiciously like a glorified “include” statement but there are differences. The main one being each composite “attach” creates a new View object which can be sourced from other Modules, and with Module specific helpers and filters (and of course Model accessing View Helpers!). If we assumed the composite method was “attach” (common Composite Pattern method), a composite template could look like:
articlelist.phtml (part of the imaginary Articles application Module):
[geshi lang=php]attach(‘stdheader.phtml’, ‘default’); ?>
summary ?>
attach(‘underbody.phtml’) ?>
attach(‘stdfooter.phtml’, ‘default’) ?>[/geshi]
overbody.phtml:
[geshi lang=php]
[/geshi]
Here we have two templates, both utilise an imaginary attach() method from the View object to attach new sub Views to the template at specific locations within the layout (you’re right in thinking attach() will handle rendering of the child View). It also allows for a template to attach Views from other Modules of the application if required (and would transparently manage the different View settings for that Module). I’ve assumed the lack of a “module” parameter means the attached View should come from the current Module only. The last overbody.phtml template allows for more dynamic parameters targeting the RSS View Helper utilised by the Blog Module’s last5headlines.phtml template where we’re using the View Helper pattern to grab headlines from the given RSS feed. We visited very similar functionality in my last post.
Of course in all this we haven’t ruled out Controller nesting completely. That too is still possible, even alongside View nesting and in a very similar fashion. Since each element attached is an independent entity you can mix and match what you want to use, even from other Modules. Of course with all this floating around we still haven’t seen usable code yet! Well, that one’s for another blog entry
.
Back to the multiplicity issue for a moment, i.e. the presumed use of multiple Zend_View instances. You can guess that Zend_View will need to be subclassed and/or a standard helper class containing the attach() implementation added. There are other issues also. For example, each View object needs to be independently configured before use – i.e. for paths, encoding, etc. In Part 4 of this series I’ll take a stab at adding finer control over creating View objects in a simple reusable fashion.
I’m sure many of you will already suspect the design pattern that will involve
.
Complex Views with the Zend Framework – Part 2: View Helper Pattern
Apr 20th
Part two of my ongoing look at the View layer of the Zend Framework turns its attention to the topic of View Helpers. The Zend Framework manual provides a fairly narrow definition of its helpers which indicates they enable complex tasks, like generating form elements, to be extracted out of views into dedicated helpers. Here I’ll try to explain in greater depth the View Helper pattern which is another of those patterns in the J2EE catalog, and which adds to the range of tasks View Helpers are capable of performing.
The simplest explanation is in the separation of layers enforced by the Model-View-Controller pattern. In a typical web application using the Zend Framework, a URI is used by the framework’s Controller architecture to select an action on a Zend_Controller_Action class to execute. This action method will then normally access the application’s Model to fetch any data it requires, operate on that data, and pass a subset of it to the View (for use in rendering templates). It’s clear to see so far, that the View by default relies on the Controller to pass it the data model it needs when rendering templates.
As in my previous post however, the View may also include any number of elements (header, footer, widgets, etc.) common to ALL pages. Many of these may require data of their own.
So what is the problem? Anytime a partial View needs extra data (the View’s Model) it needs to push calls to extra Controllers (following the current practice for the framework) in order to get that Model. This involves yet another complete dispatch cycle, with any number of classes, plugins, and operations involved. Yet in most cases this is completely unnecessary – why not just let the View request data from the Model directly?
In simple terms, the View Helper acts as a middle-man sitting between the View and the Model. It’s job in our scenario is to replace the need to nest Controllers, and give that nesting/layout control back to where it belongs – the View layer. When a View (or partial View) requires Model data not supplied by the current controller, it calls upon a View Helper to go fetch that data independently of any Controller.
Let’s take a simple example. While building a blog, we’ve decided to add the last 5 entry titles from Planet PHP to the bottom of the page – every page in fact. In keeping with promoting reusability we create a generic Zps_View_Helper_Rss class which can consume RSS, and to which we can add extra methods in the future should they be needed for other Views. This is slightly different to the current view helper description in the framework manual – here we can offer a full selection of public methods forming a fuller (read-only) interface to the underlying Model – the RSS XML.
[geshi lang=php]require_once ‘Zend/Uri.php’;
require_once ‘Zend/Feed/Rss.php’;
class Zps_View_Helper_Rss
{
protected $_channel = null;
public function __construct($url)
{
if (!Zend_Uri::check($url)) {
throw new Exception(‘RSS URL is invalid!’);
}
$this->_channel = new Zend_Feed_Rss($url);
}
public function getTitles($number)
{
$titles = array();
$count = 0;
$number = intval($number);
// Zend_Feed_Abstract implements Iterator!
while ($count <= $number && $this->_channel->valid()) {
$titles[] = $this->_channel->current()->title();
$count++;
$this->_channel->next();
}
return $titles;
}
}[/geshi]
Now comes our sample template – one of those recurring Views:
[geshi lang=php]
-
getTitles(5) as $title): ?>
[/geshi]
And not a controller in sight…;)
Of course the Model can equally be running from any datasource including the database, so there’s a lot of flexibility for these View Helper classes. I haven’t done so here, but you can probably still fit them into the current view helper convention with the single public method (in our case rss() just returning instances of the object.
Of course, there really are times when the recommended Controller _forward() (or a viable alternative) can still be useful. Reliance on plugins was suggested on the mailing list, for ACL perhaps. But the point here is that controller nesting is not required except for those exceptional cases where a View Helper just won’t cut it.
Edit: I figured it be save confusion by noting this helper could equally run from a cache of the selected RSS source which is updated separately at regular intervals (hail to cron!). Save the server making the trip on every request
.
Complex Web Pages with the Zend Framework?
Apr 19th
27 March 2008:
With the inclusion of Zend_View Enhanced as first documented, discussed and publicised in this blog series, in the Zend Framework as of 1.5.0 I’d like to thank everyone involved in the process. A few of you pioneered it’s implementation and provided immense feedback which tailored the proposal to some specific needs, others kept bringing it up on the mailing lists and to the attention of the Zend reviewers, and others still spent a lot of time converging ideas towards a unified proposal. It just goes to show that the community really does have the power to influence the big picture and get stuff done!
The rest of this series can be accessed as follows:
http://blog.astrumfutura.com/archives/283-Complex-Views-with-the-Zend-Framework-Part-3-Composite-View-Pattern.html
http://blog.astrumfutura.com/archives/285-Complex-Views-with-the-Zend-Framework-Part-4-The-View-Factory.html
http://blog.astrumfutura.com/archives/288-Complex-Views-with-the-Zend-Framework-Part-5-The-Two-Step-View-Pattern.html
http://blog.astrumfutura.com/archives/291-Complex-Views-with-the-Zend-Framework-Part-6-Setting-The-Terminology.html
Recently I’ve been involved in a long discussion about the Zend Framework on the PHP Developers’ Network forum. Our approach was to pick a simple application (we decided to borrow the Java BluePrints Pet Shop for J2EE) and starting from a basic “Hello World!” example for the Zend Framework work towards a fully functional example. Of course, one of our goals wasn’t just to “do it”, we wanted to explore the framework in greater detail, and identify how best to use, misuse, subclass, and where it was logical to even replace components should they prove deficient for our needs.
After wrangling about configuration, the advantage/disadvantage of build tools (I love Phing and cannot survive without it!), the location of the bootstrap file, and a few other odds and ends we finally put up the “Hello World!” example in subversion. Many thanks to Chris Corbyn of Swiftmailer fame for contributing the repository!
http://w3style.co.uk/devnet-projects/pet-store/trunk/
We then decided to look at how the Zend Framework implements Views. In essence, the framework isn’t as developed in that respect as its peers. A simple page is easily built using a Zend_View instance, a PHP/HTML template for a list of entries, and a few view helpers and filters. After that however, a complex page becomes progressively more difficult. This is complicated in part by the growing practice of instantiating Views using a helper function on the Controller – unfortunately this is unusable since it introduces coupling making re-use more difficult in other applications where the View has been subclassed.
Back on track, the main problem of a complex View, is that the current Controller is only aware of a subset of its own required Model (data) and the current View. So how do do you get the View to include extra sections – for example, details from Technorati for your blog – which are common to ALL pages?
The Zend Framework currently suggests using a Controller’s _forward() method – basically if your current View needs data from Technorati, then forward from the current Controller to a “TechnoratiController” to fetch it and assign it to the View, and then _forward() back. This works for simple things – but what if there are three, or even more sections? What if some sections, have additional embedded sections? How in heaven’s name are you supposed to track all those _forward()’s?
While pondering the problem, we all agreed using the Controller _forward() was not a good idea – it’s prohibitively complex, forces Controllers to become aware of other (possibly unrelated) controllers, and in general doesn’t promote reuse. I haven’t measured the performance impact of such a tactic but it can’t be good. We also determined the Zend Framework’s view helpers were of limited use being simple classes designed to offer a single public method to templates.
Finally we decided to visit two design patterns to help name the problem and offer a possible solution: Composite View and View Helper. So far we’ve just implemented a very basic Composite View (KISS) to further the brainstorming. But it shows a lot of promise in offering a simple, effective solution to building complex web pages with the Zend Framework – granted it breaks the normal practice, and takes subclassing to introduce, but it’s a reusable solution.
I’ll visit Composite View in more depth soon – for the moment here’s the J2EE BluePrints page for the design pattern: Composite View. If anyone knows of a really good example in PHP or Ruby, it would be great to hear about it!
On the View Helper bit – the Zend Framework seems to persist a belief that only Controllers should interface with the Model layer (i.e. Database and associated Model classes). This Model-Push strategy can be complemented with an equally valid Model-Pull strategy – where View Helper classes have the ability to directly access and read data from the Model to pass to the requesting View. This completely avoids the fickle tactic of Controller forwarding and the complexity it tends to introduce into an application.
Stay tuned for a deeper look at both these patterns – specifically how they can be brought to bear on the Zend Framework with a little subclassing of Zend_View.
S.T.A.L.K.E.R.: Shadow of Chernobyl
Apr 5th
I finally got my copy of the game at the weekend, played a little, got the patch, found my save games were incompatible, restarted, and replayed (sigh) a little more. It’s an interesting game, full of interesting ideas and sometimes exasperating combat. Surprisingngly, given the level of buginess so evident (and definitely not addressed by that patch) it’s a good game overall. So it gets a thumbs up from me, with a sidenote that you should have a pretty decent rig to really get the most out of the game, and should have a certain tolerance for the inevitable bug or two.
Even so, there are some spectacular misses. Gameplay stands by itself very well, so these aren’t as important as they would be to a lesser First-Person Shooter, but still… The most obvious is that the settings menu for Video Options is a mess – Antialiasing and Anistrophy are non-existent. One is simply not working, the other is useless because STALKER’s game engine uses a weird rendering system that doesn’t support it. I’ve been reading the TweakGuide.com examination released earlier and all is not lost – there are tweaks you can make since the game is capable of being modded by extracting the content archives (much like Oblivion and Medieval 2). TweakGuide also comments on the effectiveness of some low-level options (which don’t seem to work better than the “medium” ones). Also HDR, important for GeForce 6 series GPU’s, is not a separate setting to be disabled.
Back to the game play – STALKER excels at a few graphical additions (even with the above). The most obvious is the weather. When it rains, it pours. When it let’s loose lightening, your video card takes notice. The second is the day/night cycle – and night is something to really take care with. Unlike Oblivion, or other half-assed attempts at day/night cycles, STALKER just takes the realistic of approach of making the sun set and rise at genuine times. Simple, effective. Half Life 2: Episode One (the level with the underground garage populated by Zombies) is a close match for how you’ll feel when night arrives. Even bumping up the gamma level doesn’t help with visibility. Even the flash light isn’t much help beyond a certain range. This really packs a cool punch – especially when you have to spend the next 7 hours of gametime (a lot less in real time of course
) stumbling around in the dark hearing the howls of a pack of mutant dogs and barely being able to see them when get close. Sychronising attacks with lightening strikes becomes a quickly learned skill
.
The other cool thing is the “ALife”, watching mother nature at war with packs of Blind Dog mutants run into confrontations with those mutant boars around this corner, or something even weirder around another – all at random in a natural fashion. It’s cool to watch – especially once you realise those creatures have defining habits. At the start, I remember finding the body of a fellow Stalker surrounded by mutant dogs. After shooting up two, and scattering the rest I returned some hours later to find the escapees of my first attack had returned to the body and were apparently ravaging it – and their dead compatriots. I almost felt sorry for the poor sod whose pixelated body was being gnawed on, I was even tempted to use the “drag body” action to move him to a place safe from the local man-eating wildlife.
A few places where it goes wrong includes the mission system. Missions are obviously not finished in full – most are given by a handful of Traders, or Stalker leaders. Most come with no other in-game scenery, events, or NPC interaction other than the text descriptions. Oblivion was far better – of course Oblivion has voice overs for ALL the text which made it more immersive to start with. This lack of gloss in some areas, and the opposite in others is a sad thing – finished this game would have hit a few 90%+ marks in reviews, rather than the telling 80%+ it seems to be getting.
Overall, it’s flawed and buggy, but that’s easily forgiven once you jump into unique action. My score? I’d go with an 85% and hope it prods future FPS’s to new levels of originality.
Alien Assault Traders 0.30 Released!
Apr 4th
Congratulations to Mark Dickenson (aka Panama Jack) and Rick Thomson (aka Tarnus) on their recent release of Alien Assault Traders 0.30. It’s been in development for a while now and it’s cool to see the end product finally let loose
.
Alien Assault Traders is an online browser-based space strategy trading game written in PHP. It’s a fork of Blacknova Traders. If you’re looking for a free open source web game then here’s one to take a peek at. PJ is well known for focusing more than the usual effort on optimisation (he wrote the ADOdb Lite and Template Lite libraries) so it’s a bit easier on your hardware than many alternatives.
I haven’t been tracking development as much as I used to (busy with Astrum Futura, QGL and my Zend Framework proposals) but the new version has a significant overhaul of the previous 0.2x code. Have fun!

