This may sound cryptic,
so let's look at it using a real life scenario.
You are doing a project that works on a very complex system. For this example, you
are creating an online document repository, which saves documents in temporary
storage. For this you need support for PostgreSQL, MySQL, Oracle, and SQLite
because users may deploy your application using any of these. So you create an
object, which connects to MySQL and perform the necessary tasks. Your MySQL
object is:
class MySQLManager
{
public function setHost($host)
{
//set db host
}
public function setDB($db)
{
//set db name
}
public function setUserName($user)
{
//set user name
}
public function setPassword($pwd)
{
//set password
}
public function connect()
{
//now connect
}
}s
?>
Chapter 4
[ 71 ]
Well, now you use this class like this:
$MM = new MySQLManager();
$MM->setHost("host");
$MM->setDB("db");
$MM->setUserName("user");
$MM->setPassword("pwd");
$MM->connect();
?>
You can now see that before you started using your class, you needed to do a lot of
things. Your PostgreSQL class also looks similar:
class PostgreSQLManager
{
public function setHost($host)
{
//set db host
}
public function setDB($db)
{
//set db name
}
public function setUserName($user)
{
//set user name
}
public function setPassword($pwd)
{
//set password
}
public function connect()
{
//now connect
}
}
?>
And usage is also the same:
$PM = new PostgreSQLManager();
$PM->setHost("host");
$PM->setDB("db");
Design Patterns
[ 72 ]
$PM->setUserName("user");
$PM->setPassword("pwd");
$PM->connect();
?>
But now usage could be a bit difficult when you merge them together:
If ($dbtype=="mysql")
//use mysql class
Else if ($dbtype=="postgresql")
//use postgresql class
?>
Shortly after this you will find that as more database engines are added, the core
code changes significantly and you have to hard code all these things in core classes.
Pages:
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93