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

Advertisements