Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 3 ■ SINGLETON AND FACTORY PATTERNS^27

to determine which class should be called, and then call a specific class, replicating the factory’s
behavior.
This factory also makes it easy to make changes in the future. Adding another supported
image type requires only modification of the single factory method. Without the factory pattern,
you would need to update every block of code that consumed your API. In the next example, we
will examine this concept, often called future-proofing, in more depth.

The Portable Database


In PHP applications, you will typically use a relational database to store the data your applica-
tion creates and references. One of the biggest problems with databases is the inability to interact
with them in a portable and interchangeable manner. If you’ve ever ported an application from
one database to another, you’ve probably needed to refactor an extremely large amount of
code, because the possible need for such a change was not considered when the application
was developed.
With applications that use a database, the factory pattern can help you in two ways:


  • It will make it easy for your software to support many different database platforms, a
    feature which will help to expand your customer base.

  • If your software is in-house, it will guarantee that if you need to change databases, porting
    the application to another platform will be a trivial job.


Listing 3-6 demonstrates the concept of using a database factory. You may wish to create a
database table called user to test it. This table should define a single varchar column named email.

Listing 3-6. Using a Factory for Database Portability

interface IDatabaseBindings {

public function userExists($email);

}

class PGSQL implements IDatabaseBindings {

protected $_connection;

public function __construct() {
$this->_connection = pg_connect('dbname=example_db');
}

public function userExists($email) {
$emailEscaped = pg_escape_string($email);
$query = "select 1 from users where email = '". $emailEscaped ."'";
if($result = pg_query($query, $this->_connecion)) {
return (pg_num_rows($result) > 0)?true:false;

McArthur_819-9C03.fm Page 27 Friday, February 1, 2008 10:24 AM

Free download pdf