Monday, January 26th, 2009 | Author: Dave

For a long time I’ve been working to expand my OOD skills, and have read many articles, blogs and a few books. Head First Design Patterns is great, by the way. Anyway, one concept that you will come across repeatedly is that of encapsulating what varies.

Have a look at the following getUsers() method – this is a method from an AMFPHP service class that simply returns the data, for a given user, from a MySQL users table to Flash:

function getUser($id)
{	
        $sql = "SELECT * FROM users WHERE id=$id";
 
	$result = mysql_query($sql, $connector);
	if(mysql_num_rows($result) != 0){
		return mysql_fetch_array($result);
	}else{
		return -1;
	}
}

Simple enough. However, in a typical system you will have dozens of services and most of those services will have multiple methods – eg. to save, update and delete data as well. So, what happens when your shiny new system is installed on a server running PostgreSQL? Answer: You spend days changing API calls if your code looks like the above. And then you have two versions of your services. The problem is that you’ve programmed your services to work only with the MySQL API methods.

So how do you fix it? You encapsulate what varies – the database API calls. If you stick the database access stuff into its own class, and then access everything through your new database class, you remove the tight coupling you have to MySQL. If you need to change the database API calls, you only have to change one class, not the potentially hundreds that may use it. Let’s take a look at a modified version of the above method:

var $myDB;
$this->myDB = new DBAccess(); //create an instance of the DBAccess class
 
function getUser($id)
{	
	$sql = "SELECT * FROM users WHERE id=$id";
 
	$result = $this->myDB->query($sql);
	if($this->myDB->num_rows($result) != 0){
		return $this->myDB->fetch_array($result);
	}else{
		return -1;
	}
}

And over in your DBAccess class you’d define the query(), num_rows() and fetch_array() methods, along with any other database related functionality:

<?PHP
 
	class DBAccess
	{					
		function DBAccess(){}		
 
		function query($sql)
		{
			return mysql_query($sql, $this->getConnection());
		}
 
		function num_rows($result)
		{
			return mysql_num_rows($result);
		}
 
		function fetch_array($result)
		{
			return mysql_fetch_array($result);
		}		
 
		function getConnection(){			
			$con = mysql_connect("localhost", "DBUSER", "USERPASSWORD");
			mysql_select_db("DATABASENAME", $con);					
			return $con;
		}
	}
?>

If you change over to PostgreSQL you need only to modify DBAccess.php. And taking it a step further, you could put in switch statements enabling the class to use various databases.

Category: OOP
You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.