1. Description
1. Adapter Mode: 可以将截然不同的函数接口封装成统一的API
2. Practical application example, PHP database operation has MySQL, mysqli, Pdo3 species, can be unified into the same adapter mode. A similar scenario is a cache adapter that unifies different cache functions, such as MEMCACHE,REDIS,FILE,APC, into a consistent
3. The following example can help you deal with various database link functions, MySQL mysqli, PDO random selection, operation is abstracted into a unified interface client does not need to modify a row of database link mode
2. Create an interface
interface IDatabase{ function connect($host, $user, $passwd, $dbname); function query($sql); function close();}
3.Mysql Package
class MySQL implements idatabase{ protected $conn; function connect($host, $user, $passwd, $dbname ) { $conn= Mysql_connect ($host,$user,$passwd); mysql_select_db ($dbname,$conn);$this->conn =$conn; } function query($sql) { $res= mysql_query ($sql,$this->conn);return $res; } function close() {Mysql_close ($this->conn); }}
4.MYSQLI Package
class mysqli implements idatabase{ protected $conn; function connect($host, $user, $passwd, $ dbname) { $conn= Mysqli_connect ($host,$user,$passwd,$dbname);$this->conn =$conn; } function query($sql) { returnMysqli_query ($this->conn,$sql); } function close() {Mysqli_close ($this->conn); }}
5.PDO Package
class PDO implements idatabase{ protected $conn; function connect($host, $user, $passwd, $ dbname) { $conn=New\pdo ("mysql:host= $host;d bname= $dbname",$user,$passwd);$this->conn =$conn; } function query($sql) { return $this->conn->query ($sql); } function close() { unset($this->conn); }}
6. Instance invocation, (Unified interface Invocation)
$db=NewPDO ();$db->connect (' 127.0.0.1 ',' Root ',' Root ',' Test ');$db->query (' show databases ');$db->close ();$db= Mysqli ();$db->connect (' 127.0.0.1 ',' Root ',' Root ',' Test ');$db->query (' show databases ');$db->close ();$db= MySQl PDO ();$db->connect (' 127.0.0.1 ',' Root ',' Root ',' Test ');$db->query (' show databases ');$db->close ();
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
PHP design mode Adapter mode