当前位置 : 主页 > 网络编程 > PHP >

PHP设计模式之适配器模式代码实例

来源:互联网 收集:自由互联 发布时间:2021-07-03
//From http://www.lai18.com //适配目标,规定的接口将被适配对象实现interface IDatabase{ public function connect($host, $username, $password, $database); public function query($sql);} //适配器class Mysql implements IDatab
 
//From http://www.lai18.com 
//适配目标,规定的接口将被适配对象实现
interface IDatabase
{
  public function connect($host, $username, $password, $database);
  public function query($sql);
}
   
//适配器
class Mysql implements IDatabase
{
  protected $connect;
   
  public function connect($host, $username, $password, $database)
  {
    $connect = mysql_connect($host, $username, $password);
    mysql_select_db($database, $connect);
    $this->connect = $connect;
    //...
  }
   
  public function query($sql)
  {
    //...
  }
}
   
//适配器
class Postgresql implements IDatabase
{
  protected $connect;
   
  public function connect($host, $username, $password, $database)
  {
    $this->connect = pg_connect("host=$host dbname=$database user=$username password=$password");
    //...
  }
   
  public function query($sql)
  {
    //...
  }
}
   
   
//客户端使用
$client = new Postgresql();
$client->query($sql);

网友评论