master page in php

Simple MasterPages with PHP
If you are an ASP.Net developer used to working with MasterPages (or any equivalant on another framework), you may be looking for an equivalant while working with php.  I was looking to do something like that with my homepage (hoolihan.net).  This is a very simple site, where a full framework would have been overkill.
Here’s how I pieced it out:
First: Create a template page, I called mine master.php.

Second: Create a content piece, for example about_text.php.

This is information about me.

Third: Create the page with the actual name you want to use:
<?php
$page_content = ‘about_text.php’;
include(‘master.php’);
?>

<?php
$page_content = ‘about_text.php’;
include(‘master.php’);
?>

save ->  about.php

One added benefit is that the content piece is then loadable in other places if need be.
Obviously, you’ll want to add a few bells and whistles.   For example, It’s a good idea to check for $page_content being null, and provide a default in that case.  I left out some of those things for the sake of brevity.
For more patterns in php, check out the following books:
PHP Objects, Patterns and Practice (Expert’s Voice in Open Source)
PHP Object-Oriented Solutions
Basically, it’s a real simple way to cleanly break up your php pages.  Hope you found  this useful…
Update: I’ve posted a follow-up article about the ajax ideas mentioned in this article. Also, see more php posts on this blog and more programming posts.
Update 2: User Ton posted a good comment below about how to setup the content variable (and simplify your url) with apache.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s