First steps in object oriented PHP

by Kevin Partner on 27th October, 2009

PHP gets a bad press from time to time, largely because its very flexibility is seen as laxness by the tight sphincter brigade. However, just because PHP doesn’t force “best practice” on programmers doesn’t mean you can’t adopt said best practice.

Object oriented programming is much talked about and has many advantages over the old-school line-based procedural code. You’re probably familiar with functions (blocks of code called independently: they used to be called subroutines in the old days). Objects are groups of function which are, to some degree, “self aware”. By this I mean that values can be passed within the objects to allow the object to take the appopriate actions.

Enough of theory, I want to give a concrete example of how using objects can be, in a very practical, sense a timesaver. I’m going to show you how to create a very useful database object which can be used to make connecting to the database, retrieving and storing data much simpler.

Right, open up your favourite editor: mine is PHPDesigner although a good free alternative is PSPad. I’m assuming you have a working MySQL database and want to connect to it. If you’re at all familiar with interacting with MySQL, you know that there are three stages involved in retrieving information: connecting to the database, running the query and processing it. Let’s start by dealing with the first of these and automating the connection.

Create a blank PHP file and give it a name. I tend to use a two part convention: the first part of the name describes the purpose of the class, the second indicates the author. So, in this case, we might call it DbaseSB .php (SB=Scribbleit).

Here’s the inital code:

< ?php
//DATABASE CONNECTION/MANIPULATION OBJECT
//AUTHOR: KEVIN PARTNER
class DbaseSB
{
	private $DB_HOST="localhost";
	private $DB_NAME="mydbname";
	private $DB_USER="mydbuser";
	private $DB_PASSWORD="mydbpassword";
	private $connection;

You can see that we begin with the keyword “class” followed by the name of the class. This MUST be the same as the name of the PHP file. Following this is a series of variable definitions. private indicates that these variables are only accessible within the object: this is for security reasons and because these variables are only needed by the database object.

The variable names should be self explanatory except for $connection which is a variable I’m going to use to store the database connection once it’s made.

Now for the next bit:

function __construct()//CONSTRUCTOR FUNCTION WHICH IS RUN WHEN THE OBJECT IS CREATED
	{
		$this->connection = mysql_connect($this->DB_HOST, $this->DB_USER, $this->DB_PASSWORD) or die("unable to connect to database");

		$db_select=mysql_select_db($this->DB_NAME,$this->connection);

		if(!$db_select)
		{
			die("Database selection failed: ".mysql_error());
		}
	}

This code immediately follows the first block. The __construct magic method is run automatically when the object is created (we’ll see how to do that in a bit) so what this code achieves is to create a database connection automatically using the details you’ve supplied. This connection is then stored in the $connection variable for use later.

You’ll notice that $connection is expressed as $this->connection. The identifier $this represents the current object so what it’s saying is “my copy of $connection” since you could have many objects running at once based on a single class.

Moving right along, this code immediately follows the last block:

	function query($query)
	{
		$querydata=mysql_query($query);
		$this->confirm_query($querydata);
		return($querydata);
	}

	function confirm_query($result_set)
	{
		if (!$result_set) {
			die("Database query failed: " . mysql_error());
		}
	}

The first method (functions are called methods when they’re inside an object, go figure) wraps up any MySQL query and runs it. confirm_query checks to see that a valid result was achieved and, if not, echoes out the error returned.

Now, this might seem like a lot of work just to do some database stuff but the beauty is that you only have to do it once (and you can, after all, copy and paste it from here). This class can now connect to a database and execute a query. All that’s left now is to add some general purpose queries that will shield you from having to remember the MySQL code.

So, let’s now add one such general purpose method:

	function fetchfield($table,$indexname,$indexvalue,$fieldname)
	{
	    $query="SELECT * FROM $table WHERE $indexname=$indexvalue";
	    $querydata=$this->query($query);
	    $fielddata=mysql_fetch_assoc($querydata);
	    return $fielddata[$fieldname];
	}
}
?>

As its name suggests, fetchfield will pull out a single field from a single row of a database.

Ok, that completes our class for now: let’s look at how we would use that in a PHP script. So, create a script (for example “index.php”) in the usual way. For now, I suggest putting it in the same folder as the class but that’s not generally a good idea as it’s best to have your classes all together.

< ?php
require_once("DbaseSB.php");
$dbobject=new DbaseSB();

$userid=1001;

$firstname=$dbobject->fetchfield("users","userid",$userid,"firstname";
echo($firstname);
?>

In the first line, we include the php class file. The second line shows how to create an object from the class. A “class” is the blueprint, the definition of the object. Just as you can build many houses from one blueprint, you can create as many objects as you like from one class and each can have its own variable values etc. Most often, you’ll just create a single copy as here.

Important note:Remember that, in creating (“instantiating”) our object, it automatically connects to the database: you don’t have to carry out that step.

We then define a variable for testing purposes. On the next line, you can see how we access our object’s single method, fetchfield. In this case, the table name is “users”, the index we’re using to identify the row containing the field is called “user id”, the actual value of userid is $userid and the field we want to fetch is “firstname”.

A very simple but powerful example. Now that the object is created, we can use it anywhere on this page without recreating it. Adding new methods makes it progressively more powerful, allowing you to use MySQL without using MySQL, if you see what I mean. That single line of code has replaced at least 7 lines if you don’t include the connection. The more complex the method, the greater the time saving.

Furthermore, each time you add a method it becomes available across your whole site AND you can up and move your entire library to a new site for a new project and all you need to change is the connection information. Convinced yet?

Share and Enjoy:
  • Print
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Add to favorites

{ 2 comments… read them below or add one }

JP February 1, 2010 at 10:08 am

Hi Kevin

You don’t need to post this, but the PHPDesigner link above goes to a parked website.

The correct link is

http://www.mpsoftware.dk/phpdesigner.php

Brgds

kevin.partner February 1, 2010 at 10:28 am

Sorry about that…link now edited

Leave a Comment

Previous post:

Next post: