In college we learn to use the FACTORY
template for connections, but I wonder if it is possible to apply interfaces as well, as in the following example:
Case study
I have an application in php that follows as closely as possible the MVC
pattern, but that should have the connection independent, that is, if it is necessary to change the bank, there was no need to rewrite the whole application.
Then, a class named MySQ_LConnect
was created in the model, which provides connection to the Mysql
database, as well as the execution of the querys
that is passed to it:
class MYSQL_connect {
private $hostname = 'myHost';
private $username = 'DBUser';
private $senha = '';
private $banco = 'database';
private $conn;
public function conectar(){
$this->conn = mysql_pconnect($this->hostname, $this->username, $this->senha);
$db = mysql_select_db($this->banco,$this->conn);
return $this->conn;
}
public function executarQuery($query,$conn){
$result = mysql_query($query,$conn);
return $result;
}
public function desconectar($conn){
mysql_close($conn);
}
Considering a future migration to sql server
, a connection class was created for this bank and an interface, just to parameterize the two existing connection classes:
Interface
interface iConnect{
public function conectar();
public function executarQuery($query,$conexao);
public function desconectar($conexao);
}
Connection class with sqlserver
class MSSQL_connect implements iConnect{
private $hostname = 'myHost';
private $connInfo = array("Database"=>"database", "UID"=>"DBUser", "PWD"=>"");
private $conn;
public function conectar(){
$this->conn = sqlsrv_connect($this->hostname, $this->connInfo) or die(sqlsrv_errors());
return $this->conn;
}
public function executarQuery($sql,$conn){
$result = sqlsrv_query($conn,$sql,array(),array("Scrollable"=>"buffered"));
return $result;
}
public function desconectar($conn){
sqlsrv_close($conn);
}
}
Note: in class MYSQL_connect
the interface has been implemented too.
Then, in the test environment, you can switch between banks using a Fabrica
connection, where BANCO
is a prefix of banks (just to make it easier to switch between banks):
require_once 'MySQL_connect.php';
require_once 'MSSQL_connect.php';
define("BANCO","MySQL");//ou pode ser MSSQL
class Fabrica{
public function fabricar(){
$classeDAO = BANCO."_connect";
return new $classeDAO;
}
}
Doubt
How to use interfaces in this case to abstract the connection type, similar to what the Fabrica
class is trying to do, so that for the rest of the application it makes no difference what bank is connecting to?
If the interface does not meet this requirement well, how to abstract without using Factory
?