Thursday, June 4, 2009

php5 interfaces

PHP5 supports "interfaces".
What is an interface ? Basically, it's a definition of a class type with methods. If you implement an interface, you must write all the methods in that interface.

Example:
Let's suppose there is a "dbConnection" interface, that contains all the methods to db access.

Interface dbConnection
{
public function __construct($host, $user, $pass, $db);
public function query($q);
public function getError();
public function getAffectedRows();
public function nextRow();
/
/[...]
}


Now you can already write an application that use the methods of the interface, regardless of the implementation of the methods.

//application
$db = new MySQL("localhost","user" [...]);
$db->query("select * from table");
while (
$row = $db->nextRow())
print
"{$row->field1} {$row->field2}"

Let's write the class for MySQL access

class MySQL implements dbConnection
{
private $conn;
public function
__construct($host, $user, $pass, $db)
{
$this->conn = mysql_connect($host, $user, $pass);
mysql_select_db($db, $this->conn);
}
//[..
other methods...]
}


And a class for SQLite

class SQLite implements dbConnection
{
private $conn;
public function
__construct($host, $user, $pass, $db)
{
$this->conn = sqlite_open($db);
}
//[.. other methods]
}


Now if want to change the application and use SQLite instead of MySQL, you have to modify ONLY the 1st line:

$db = new SQLite("","","","/path/to/file.db");

You don't need to check the rest of the code. MySQL and SQLite classes implements the same interface (and the same methods) !
Interfaces improve your code !

No comments:

Post a Comment

 

PHP and tips|PHP