mardi 11 juillet 2017

Adapter Pattern without the use of Adapter Interface?

I was reading a book that introduces the use of Adapter Pattern. It said that The Adapter pattern is frequently used in web projects as a way to make use of a database API (such as PDO or mysqli) without coupling the pages over and over to that database API. Below is the sample code:

interface DatabaseAdapterInterface
{
 function setConnectionInfo($values=array());
 function closeConnection();
 function runQuery($sql, $parameters=array());
 function fetchField($sql, $parameters=array());
 function fetchRow($sql, $parameters=array());
 function fetchAsArray($sql, $parameters=array());    
 function insert($tableName, $parameters=array());
 function beginTransaction();
 function commit();
 function rollBack();
 //many other methods
}

class DatabaseAdapterPDO implements DatabaseAdapterInterface
{
 //implements all the methods in the DatabaseAdapterInterface
 }

 class DatabaseAdapterMySQLi implements DatabaseAdapterInterface
 {
 //...implements all the methods in the DatabaseAdapterInterface
 }

Any client classes (or pages) that needs to make use of the database will do so via the concrete adapter:

$connect = array(DBCONNECTION, DBUSER, DBPASS);
$adapter = new DatabaseAdapterPDO($connect);
$sql = 'SELECT * FROM ArtWorks WHERE ArtWorkId=?';
$results = $adapter->runQuery($sql, array(5));

While this sample code clearly contains no PDO code, it is not exactly free from dependencies to our database API.

I got the idea, but I don't know why we need to have the DatabaseAdapterInterface? We can just define all the methods in DatabaseAdapterPDO and DatabaseAdapterMySQLi without the use of DatabaseAdapterInterface, we can save some code efforts to write DatabaseAdapterInterface, can't we? Or the use of DatabaseAdapterInterface can force programmer to implement required methods so programmers will not miss any required method?

Aucun commentaire:

Enregistrer un commentaire