Roll Your Own PHP Framework: Part II
A little over a week ago, we looked at how to set up our file structure and how to get URL routing working in our little framework. So we now have something to handle urls and display a page, but we want to make the page a little more attractive. Since there is nothing fun about making php print html, let’s add a template piece to the puzzle. We won’t have to do too much since php is a great template language by itself.
Mini-series Overview
- Part 1: URL Routing and Directory Setup
- Part 2: Templating
- Part 3: Database Interaction
Note: I’m assuming you have a little OOP (Object Oriented Programming) experience. There are a ton of tutorials out there, so just a heads up: I won’t be teaching/explaining OOP here.
We are going to create a class Template and add a little code to it so it will return our pretty new page to our browser.
Wipe out system/template.php and add the following code to it:
<?php
// We are creating a simple class here to handle our templating.
// All this class will do is set some variables and return
// a rendered webpage using native php as the template language.
class Template
{
// We setup $pageVars to hold all our pages
// variables.
private $pageVars = array();
// We setup $template to define what file is our
// template and were to get it.
private $template;
// When a new Template object is instantiated we want to make sure
// we pass it a shortened path to the file we want it to use
// as our template.
// example: $template = new Template("helloworld/templates/helloworld.php");
public function __construct($template)
{
// We setup our action directory
$actionsDirectory = PEANUT_ROOT_DIR . 'actions';
// Let's build and set our class var $template to the
// value of $template that was passed into our __construct method
$this->template = $actionsDirectory . '/' . $template;
}
// Now we create out set method to allow use to set variables that
// we want in the template.
// So in our page action we would do:
// $template->set("title", "hello world");
// and in our template:
// <h1><?php echo $title; ?></h1>
public function set($var, $val)
{
// This may look weird, but it's not to bad;
// what we are doing is setting the index name
// of our associative array pageVars
// (we setup earlier at the top of the class)
// to the value that we pass. so $pageVars["yourVar"] = "yourValue"
// is basically what it's doing.
$this->pageVars[$var] = $val;
}
// To render we will need to do a couple of things.
// First we will need to extract those pageVars then
// include the template, populate the values in the template
// and return a rendered page to the browser
//
// This is far more easy than you think it is
// trust me!
public function render()
{
// The extract function is a weird bird
// when you call it on an associative array
// it creates regular vars.
// For instance:
// $this->pageVars["yourVar"]
// becomes:
// $yourVar
// so basically we are converting all the
// index keys (with their values), in pageVars to
// their own respected variables
extract($this->pageVars);
// Now that we have all the variables extracted, the vars we set
// in the template will be replaced by the value of the pageVars variables.
// Now we start up our output buffer, grab our template and return the
// buffer with it's "rendered" template
ob_start();
require($this->template);
return ob_get_clean();
}
}
Well hello templating! Now let’s do a couple of things to hook it up to our framework. First, let’s open up our www/index.php one more time and add the following line:
require(PEANUT_ROOT_DIR . ’system/template.php’);
Right underneath the dispatch.php require statement. Now let’s change our actions/helloworld/actions.php mypage function to look like:
// We simply define the function (the second item in our request url)
// making sure it is the same name as the one in the url.
function mypage()
{
// Let's create a new template object and pass it the path to our template
$template = new Template("helloworld/templates/helloworld.php");
// Set our page variable "title" with the value "Hello World"
$template->set('title', 'Hello World');
// Set our page variable "message" with our little message
$template->set('message','This is my first message for my template');
// Now we can call render and return it to dispatch to
// display in our browser
return $template->render();
}
Ok, so now our page action is setup to use our new found template class, now we need to setup our template
So inside actions/helloworld/templates/helloworld.php template put the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>My PEANUT Page</title>
</head>
<body>
<!--
See how we use native php here?
echo out a variable, this is the same
variable name that you use in your template
set method ($template->('title', "hello")).
-->
<h1><?php echo $title ?></h1>
<p><?php echo $message ?></p>
</body>
</html>
Ok, so let’s see where we are at. We have basic url routing, templating, and page actions. We are only missing one thing, a way to talk to the database! That will be the next and final article in our mini-series on rolling your own PHP Framework.
Since the days of the Commodore 128, Wess has become an expert in C, C++, Java, Javascript, Python, and PHP and he also has extensive knowledge of Objective-C/Cocoa, Ruby, and Erlang. His blog can be found at www.wattz.net.


I must say, this is pretty awesome!
I can’t wait for the final part to piece it all together!
Thank you very much! They’re interesting and helpful :)
Thanks for the posts. We are currently in the designing phase of our framework, and have taken a few tips from your approach. I’m just waiting to see how your model works.
Hey, Caleb you can check out the framework that inspired me to write the article. A framework I have been working on at: Actionleaf.googlecode.com. It’s a lot like django, and a few other frameworks. We borrowed things we liked from various frameworks.
Thanks for reading!
I love how simple your framework is, unlike some framework’s source I’ve looked at, yours is an easy read. It’s a simple and to the point framework. Thanks for the link, and keep up the good work!
Very interesting approach. Can’t wait for the next part. I hope that you make more articles about how to increase the features of the site in the future.
Nice work, Wess. I wish all programmers commented as well as you do. ;)
Great tutorial. When will part III be published?
Thanks for this. Please tell me that this is not going to be yet another abandoned “roll your own php framework” tutorial series.
I am eagerly anticipating part 3!!!
@Trond and @djheru . It is not abandoned! I actually already have Part III from Wess, and will be posting tomorrow morning. We have a great TextPattern article going up today. So one more day ;)
I refreshed all day yesterday looking out for Part III but it didn’t appear like you said? Can we have it today please?
Pretty please?
Really good series, I had no clue about writing a framework but I now have a project up and running. Thanks heaps
Looking forward for part 3!!
Great tutorial, thanks :)
OK, Part III has been posted… I can’t apologize enough for the delay. The delay was with me, not Wess. I’ll try to keep that from ever happening again :(. Hope you guys enjoy part three: http://fuelyourcoding.com/roll-your-own-php-framework-part-iii/
u really rock man!
:)
these tuts are awsome. now i can understand how frameworks work.
thanks man.