Simple Blog – Example 7: Smarty

Simple Blog is a multi-part series. Check out The Index

In the previous example, we improved our application’s models by rewriting the Database and Post classes using PHP Data Objects. In this example, we’ll shift focus to our application’s views. Until now, we’ve been using PHP’s own engine to render our view pages. Our view pages were made up of HTML interspersed with small block of PHP to import header and footer markup, iterate through arrays, and display the contents of variables. In this example, will integrate the Smarty Template Engine into our application which promises to truly separate presentation logic (HTML/CSS) from application logic (PHP).

In the process of researching this post, I hit up smarty.net to read up on the advantages of implementing their template engine. They claim that Smarty makes the development process easier, faster, and more maintainable. On the flip side, Smarty openly acknowledges that installing their template engine results in slower script execution as compared to native PHP. Obviously, introducing an additional layer of complexity to page rendering will result in slower execution; but how much slower? We’ll get to that …

So, let’s take a look at what Smarty has to offer. We’ll start by looking at our configuration file, where we’ve made a few administrative changes to get Smarty working. FYI, if you’re following along, take a look at Smarty’s quick install guide before proceeding.

Configuration File

Instead of listing the entire config file, I’d like to highlight just the lines relevant to installing Smarty. First, we define an absolute path to the Smarty directory:

define('SMARTY_PATH', INCLUDE_PATH.'smarty'.DS);

Next, we import the Smarty class:

require_once(SMARTY_PATH.'libs'.DS.'Smarty.class.php');

Continue reading

Simple Blog – Example 6: PDO

Simple Blog is a multi-part series. Check out The Index

In the last example, Simple Blog – Example 5, we rewrote the application’s data logic using PHP’s mysqli extension. In this example, we’ll rewrite the application’s data logic again, but this time using PHP Data Objects. PDO offers significant advantages over PHP’s original mysql extension.

First, PDO offers a fully object-oriented interface through its PDO, PDOStatement, and PDOException classes. Second, PDO helps protect our application from SQL injection attacks by using parameterized statements. Third, PDO offers transactional support to commit or rollback multiple statements at once. Finally, PDO offers a consistent interface across multiple database drivers which greatly enhances the portability of our application.

Database Class

Since PDO already offers an object oriented interface, I decided not to write a wrapper class. The new Database class extends the PDO class and performs the simple task of connecting to the database engine and selecting the target database.

class Database extends PDO 
{
	public function __construct() 
	{	    
	    try 
	    {
	   		// Build PDO data source name for MySQL connection
		    $dsn = "mysql:host=".DATABASE_HOST.";dbname=".DATABASE_NAME;

		    // Open database connection
			parent::__construct($dsn, DATABASE_USER, DATABASE_PASSWORD);	
		}
		catch (PDOException $exception) 
		{
			die($exception->getMessage());
		}
	}
}

Continue reading

Simple Blog – Example 5: MySQLi

Simple Blog is a multi-part series. Check out The Index

Until now we’ve been exploring different programming styles. We programmed the Simple Blog application using structured, procedural, and object oriented programming. Next, we explored the MVC pattern by physically separating our data, application, and presentation logic. So far, each example has required pervasive changes to the application. For the next few examples, however, we’ll focus on improving specific layers of the application, rather than rewriting the application as a whole.

In this example we’ll be revisiting Simple Blog’s data access layer. PHP offers three options for interacting with a MySQL database: mysql, mysqli, and pdo. So far, we’ve only used the original mysql interface. So, let’s rewrite the Database and Post classes using mysqli. The two mysqli benefits I’m most interested in are the object-oriented interface and the support for prepared statements.

Database Class

Since mysqli already offers an object oriented interface, I decided not to write a wrapper class for mysqli like we did for the original mysql interface. The new Database class extends the mysqli class and performs the simple task of connecting to the database engine and selecting the target database.

class Database extends mysqli 
{
	private $hostname;
	private $username;
	private $password;
	private $database;
	
	public function __construct() 
	{
		// Initialize object with database constants
		$this->hostname = DATABASE_HOST;
		$this->username = DATABASE_USER;
		$this->password = DATABASE_PASSWORD;
		$this->database = DATABASE_NAME;	
		
	    // Open database connection
		parent::__construct(
			$this->hostname, 
			$this->username, 
			$this->password, 
			$this->database
			);
	}

}

Continue reading

Simple Blog – Example 4: MVC

Simple Blog is a multi-part series. Check out The Index

In example 1, we started out by writing some PHP scripts that executed pretty much top to bottom. In example 2, we re-factored our code and markup into reusable function and templates to minimize repetition in the development process. In example 3, we identified a couple candidate objects which we rolled into classes to enhance code maintainability. Throughout this process, we’ve extracted our data logic from our base pages, however, application logic and presentation layer are still mixed.

In this example, we’ll decouple application logic and presentation logic by moving all of our presentation logic into new files we’ll call views. Once we’ve performed this decoupling, our code will be nicely separated into three distinct types: models, views, and controllers.

Models

Our model is just the Post class we created in Example 3. I’ve renamed the file to ‘post.model.php’ and moved it into a directory called models, but other than these two administrative changes, the Post class is unchanged.

Views

Simple Blog has three views: List View, Read View, and Upsert View. The List View displays a list of posts. The Read View displays a single post. The Upsert View displays an HTML form for either creating a new post or editing an existing post. So, let’s take a look at our three views. Note, there is zero new code here, the only thing we’re changing is how the code is organized.

List View

<?php require_once(VIEW_PATH.'header.inc.php'); ?>

	<?php foreach($posts as $post): ?>

		<h4>
			<a href="read.php?id=<?php 
				echo $post->id;?>"><?php 
				echo $post->title;?>
			</a>
		</h4>

		<p>
			<?php echo $post->content;?>
			<?php echo $post->created;?>
		</p>

	<?php endforeach; ?>

<?php require_once(VIEW_PATH.'footer.inc.php'); ?>

Continue reading

Simple Blog – Example 3: Object Oriented

Simple Blog is a multi-part series. Check out The Index

In the previous example, Simple Blog – Example 2, we rolled-up our repetitive code and markup into functions and templates. Furthermore, we grouped functions according to their problem domain. For example, we pushed all of the generic database operations into a file called database.inc.php and pushed all of the post operations into a file called post.inc.php.

In this exercise, we’ll take each of these function groups and roll them into their own classes. First, we’ll create a Database class to facilitate basic database operations such as connect, execute, fetch, and close. Next, we’ll create a Post class to automate the process of selecting, updating, inserting, and deleting data from our post database table.

Database Class

First, let’s take a quick look at the overall layout of the database class.


	class Database 
	{
		private $connection;
		private $hostname;
		private $username;
		private $password;
		private $database;
		
		public function __construct()
		{
			...
		}

		public function openConnection()
		{
			...
		}

		public function closeConnection()
		{
			...
		}

		public function executeStatement($statement)
		{
			...
		}
	
		public function executeSql($sql)
		{
			...
		}

		public function executeDml($dml)
		{
			...
		}
		
		public function sanitizeInput($value)
		{
			...
		}
	}

Now, let’s look at a few key methods in the Database class.

Continue reading

Simple Blog – Example 2: Procedural

Simple Blog is a multi-part series. Check out The Index

There is a lot of cleanup to do after Example 1: Structured Programming. In this example, we’ll focus on cleaning up repetitive blocks of code and markup by using functions and includes.  Using a procedural programming style, we’ll transform our code from page-level scripts, to functional blocks of code and markup that can be reused throughout the application as required. The four main areas we’ll rethink and rewrite are:

  1. Directory Structure
  2. Site Configuration
  3. Page Layout
  4. Reusable Functions

1. Directory Structure

In this example, we’ll be extracting blocks of code and markup from our pages and storing them in external files which can be imported back into our base pages as required. To differentiate between our base pages and our includes, let’s start by creating a new directory named ‘includes’. We’ll use this directory to store all configuration, layout, and function files which will be imported into our base pages. Note, in a production application, you would secure this directory by creating it above your application’s root directory.

Next, instead of storing all include files in the include directory, let’s create two more sub-directories named ‘functions’ and ‘templates’. These sub-directories will help us further differentiate between blocks of code which will be stored in ‘functions’ and blocks of markup which will be stored in ‘templates’.

2. Site Configuration

Our site configuration file we’ll help setup site-wide default values such as default timezone, default currency, and default database credentials. It also helps us setup absolute paths to our base directory and our includes, functions, and templates directories. Finally, the configuration files gives us a central location to import functions that will be used on each and every page.

Continue reading

Simple Blog – Example 1: Structured

Simple Blog is a multi-part series. Check out The Index

The first example of the Simple Blog application is developed using a structured programming style. Each page is self-contained having no dependency on external functions, libraries, or layout templates. As a result, the application’s content, presentation, and behavior layers are all meshed together and any layout, configuration, or functional changes will need to be applied to each and every page.

Now, from an end-user’s perspective, Simple Blog always looks and behaves identically so no sweat of their back if a password needs to be updated in a million places, but from a developer’s standpoint this approach presents a copy and paste nightmare. In the next example, Simple Blog – Example 2, we’ll clear up many of these problems using procedural programming, but for now, here’s the structured programming approach.

1. List

To display a list of all blog posts, the program has to perform two key tasks:

  1. Pull a listing of all blog posts from the database
  2. Loop through the database results and print each row as html.

Here’s the source code for each of these tasks:

1) Pull a listing of all blog posts from the database


	// Initialize database credentials
	$host = 'localhost';
	$user = 'blog';
	$password = 'secret';
	$dbname = 'blog';

	// Build database query
	$sql = 'select * from post';

	// Open database connection
	$connection = mysql_connect($host, $user, $password)
		or die(mysql_error());

	// Select target database
	mysql_select_db($dbname, $connection)
		or die(mysql_error());

	// Execute database query
	$result = mysql_query($sql, $connection)
		or die(mysql_error());

	// Initialize rows array
	$rows = array();

	// Fetch rows from database cursor
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
		$rows[] = $row;
	}

	// Close database connection
	mysql_close($connection);

Continue reading

Simple Blog – Data Model

Simple Blog is a multi-part series. Check out The Index

Pretty simple really. Maybe too simple =) Here’s the DDL to create the database objects used throughout the Simple Blog examples.

##################################################
# Create Database
##################################################
CREATE DATABASE if not exists blog;

GRANT all privileges on blog.*
	to 'blog'@'localhost'
	identified by 'secret';

##################################################
# Create Table
##################################################
USE blog;

CREATE TABLE post (
	id int not null auto_increment primary key,
	title varchar(255) not null,
	content text not null,
	created timestamp not null default current_timestamp
);

##################################################
# Sample Post
##################################################
insert into post (title, content) values ('1st Blog Post', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi.');

Continue reading

Simple Blog – User Interface

Simple Blog is a multi-part series. Check out The Index

Please remember, this is NOT a tutorial about rolling your own blog. This series is about exploring different PHP methodologies to solve the same problem so that we can compare and contrast the pros and cons of each approach. The application we’ll be developing over and over again throughout this series is a simple blogging app that allows the user to create, read, update, and delete blog posts stored in a MySql database. Here’s a quick rundown of the end-result.

The index page pulls all posts from MySQL and displays them as HTML:

  1. The programming styles used; in this case CodeIgniter.
  2. Link to create a new blog post.
  3. Link to read a single blog post.
  4. The blog post’s content and date created.

Continue reading