工厂类是指包含一个专门用来创建其他对象的方法的类,工厂类在多态性编程实践中是至关重要的,它允许动态的替换类,修改配置,通常会使应用程序更加灵活,熟练掌握工厂模式高级PHP开发人员是很重要的。
工厂模式通常用来返回符合类似接口的不同的类,工厂的一种常见用法就是创建多态的提供者,从而允许我们基于应用程序逻辑或者配置设置来决定应实例化哪一个类,例如,可以使用这样的提供者来扩展一个类,而不需要重构应用程序的其他部分,从而使用新的扩展后的名称 。
通常,工厂模式有一个关键的构造,根据一般原则命名为Factory的静态方法,然而这只是一种原则,工厂方法可以任意命名,这个静态还可以接受任意数据的参数,必须返回一个对象。
基本的工厂类
06 |
public static function factory(){ |
07 |
return new MyObject(): |
12 |
$instance =MyFactory::factory(); |
08 |
class Image_PNG implements IImage{ |
10 |
private $_width , $_height , $_data ; |
12 |
public function __construct( $file ){ |
17 |
private function _parse(){ |
24 |
public function getWidth(){ |
27 |
public function getHeight(){ |
28 |
return $this ->_height; |
31 |
public function getData(){ |
38 |
class Image_JPEG implements IImage{ |
40 |
private $_width , $_height , $_data ; |
42 |
public function __construct( $file ){ |
47 |
private function _parse(){ |
54 |
public function getWidth(){ |
57 |
public function getHeight(){ |
58 |
return $this ->_height; |
61 |
public function getData(){ |
70 |
public static function factory( $file ){ |
71 |
$pathParts = pathinfo ( $file ); |
72 |
switch ( strtolower ( $pathParts [ 'extension' ])) |
75 |
$ret = new Image_JPEG( $file ); |
78 |
$ret = new Image_PNG( $file ); |
85 |
if ( $ret instanceof IImage){ |
2 |
$image =ImageFactory::factory( '/path/to/my.jpg' ); |
4 |
echo $image ->getWidth(); |
使用工厂类解决数据库可移值性问题
在数据库应用程序中,工厂模式可以在以下两个方面起作用。
1.使软件更容易支持各种不同的数据库平台,用于扩展用户群
2.如果软件是内部使用,需要修改数据库时,可以容易将应用程序移值到别一个平台
在代码中,创建了一个名为User的数据库表来测试它,这个表定义一个名为email的varchar类型字段
02 |
interface IDatabaseBindings{ |
03 |
public function userExists( $email ); |
06 |
class PGSQL implements IDatabaseBindings{ |
07 |
protected $_connection ; |
09 |
public function __construct(){ |
11 |
$this ->_connection=pg_connect( 'dbname=example_db' ); |
14 |
public function userExists( $email ){ |
16 |
$emailEscaped =pg_escape_string( $email ); |
17 |
$query = "select 1 from users where email='" . $emailEscaped . "'" ; |
18 |
if ( $result =pg_query( $query , $this ->_connection)){ |
19 |
return (pg_num_rows( $result )>0)?true:false; |
27 |
class MYSQL implements IDatabaseBindings{ |
29 |
protected $_connection ; |
31 |
public function __construct(){ |
33 |
$this ->_connection=mysql_connect( 'localhost' ); |
34 |
mysql_select_db( 'example_db' , $this ->_connection); |
37 |
public function userExists( $email ){ |
39 |
$emailEscaped =mysql_real_escape_string( $email ); |
40 |
$query = "select 1 from users where email='" . $emailEscaped . "'" ; |
41 |
if ( $result =mysql_query( $query , $this ->_connection)){ |
42 |
return (mysql_num_rows( $result )>0)?true:false; |
50 |
class DatabaseFactory{ |
52 |
public static function factory(){ |
53 |
$type =loadtypefromconfigfile(); |
应用程序不必知道它与何种类型的数据库连接,只会基于IDatabaseBindings接口定义的规则直接与工厂返回的实例打交道。
//调用DatabaseFactoy $db=DatabaseFactory::factory(); $db->userExists('person@example.com');
(责任编辑:admin) |