However, a very good practice of programming is loose coupling. Here you make a
separate class called DBManager, which will perform all these things from a central
place. Let's make it:
class DBManager
{
public static function setDriver($driver)
{
$this->driver = $driver;
//set the driver
}
public static function connect()
{
if ($this->driver=="mysql")
{
$MM = new MySQLManager();
$MM->setHost("host");
$MM->setDB("db");
$MM->setUserName("user");
$MM->setPassword("pwd");
$this->connection = $MM->connect();
}
else if($this->driver=="pgsql")
{
$PM = new PostgreSQLManager();
$PM->setHost("host");
$PM->setDB("db");
$PM->setUserName("user");
Chapter 4
[ 73 ]
$PM->setPassword("pwd");
$this->connection= $PM->connect();
}
}
}
?>
Context
Concrete product
Factory
Database driver
Now you can use it from a single place called DBManager. This makes the thing a
whole lot easier than before.
$DM = new DBManager();
$DM->setDriver("mysql");
$DM->connect("host","user","db","pwd");
?>
This is the real life example of a Factory design pattern. The DBManager now works
as a Factory, which encapsulates all the complexities behind the scene and delivers
two products.
Pages:
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94