Simon Willison’s Weblog


Classes for pages

15th February 2003

This weekend I started work on my latest web project, further details of which will no doubt follow soon. For the moment I’ll just say that it follows the classic news/articles/users with logins model—basically another small-to-medium sized PHP content management system.

This time I told myself firmly that I wasn’t going to reinvent the wheel and I wasn’t going to build myself yet another web framework library. I had a look at a whole bunch of Open Source systems (mostly thanks to opensourceCMS but none of them seemed to fit my (admittedly pretty stringent) requirements. I was looking for something flexible and easily modified with a well defined API, strictly standards compliant, structural/semantic templates, excellent CSS support, an easily extended user and permissions system, a powerful but straight forward control panel and a well designed, object oriented code base. It also had to be suitable for a team of programmers to hack on together, as the site will be maintained by a group of coders. With requirements like that maybe it’s not surprising that nothing fitted the bill, so I resigned myself to starting from scratch.

I said I wasn’t going to build a framework, and that really was my intention, but yesterday afternoon I hit on an idea that just got my itching to write some code. The way I see it, the structure of an HTML page is just asking to be represented with a class. All pages have a doctype, a title, a head with a bunch of script / link elements, and a body. Further more, almost all CSS designs depend on a number of div elements one after another in the body. Using these points as guidance, I quickly created a Page class that was capable of gathering this information over time until the display() method prompted it to render itself as HTML, or XHTML if that doctype was specified.

This class on its own is not much use, but the beautiful thing about using classes is that they can be extended. I created a second class, SitePage, which extended Page and performed some site specific cusotmisations such as adding the standard site header and menu divs and setting the stylesheet. Further extensions of this class will allow me to create more specialised templates for specific areas of the site. The code I have so far only took a few hours to write and is already proving to be a very productive way of controlling the overall look of the site.

My original intentions may have gone up in smoke, but I’m very happy with the code that’s been developing. I just hope it stands up to the scrutiny of my fellow coders... if not, it’s definitely been a productive learning experience.

This is Classes for pages by Simon Willison, posted on 15th February 2003.

Next: micro_httpd

Previous: Image Drag bookmarklet fixed

Previously hosted at