zoukankan      html  css  js  c++  java
  • PHP设计模式_适配器模式

    将各种截然不同的函数接口封装成统一的API。
    PHP中的数据库操作有MySQL,MySQLi,PDO三种,可以用适配器模式统一成一致,使不同的数据库操作,统一成一样的API。类似的场景还有cache适配器,可以将memcache,redis,file,apc等不同的缓存函数,统一成一致。
    首先定义一个接口(有几个方法,以及相应的参数)。然后,有几种不同的情况,就写几个类实现该接口。将完成相似功能的函数,统一成一致的方法。

    <?php
    //定义一个接口规范
    interface Database{
        protected $db;
        public function connect($host,$username,$password,$dbname);
        public function query($sql);
        public function close();
    }
     
    //下面是MySQL,MySQLi,PDO类,分别实现了接口中的所有方法
    class MySQL implements Database{
        public function connect($host,$username,$password,$dbname){
            $this->db=mysql_connect($host,$username,$password);
            mysql->select_db($dbname);
        }
        public function query($sql){
            return mysql_query($sql);
        }
        public function close(){
            mysql_close($this->db);
        }
    }
     
    class MySQLi implements Database{
        public function connect($host,$username,$password,$dbname){
            $this->db=mysql_connect($host,$username,$password,$dbname);
        }
        public function query($sql){
            return mysqli_query($this->db,$sql);
        }
        public function close(){
            mysqli_close($this->db);
        }
    }
     
    class PDO implements Database{
        public function connect($host,$username,$password,$dbname){
            $this->db=new PDO("mysql:host=$host;dbname=$dbname",$username,$password);
        }
        public function query($sql){
            return $this->db->query($sql);
        }
        public function close(){
            $this->db=null;
        }
    }
    //下面为测试代码   //只需要实例化需要的对象就可以了,规则是一致的
    $db=new MySQL();
    $db->connect("localhost","root","123456","test");
    $result=$db->query("select * from user where id = 1");
    $db->close();
     
    $db=new MySQLi();
    $db->connect("localhost","root","123456","test");
    $result=$db->query("select * from user where id = 1");
    $db->close();
     
    $db=new PDO();
    $db->connect("localhost","root","123456","test");
    $result=$db->query("select * from user where id = 1");
    $db->close();
    ?>
  • 相关阅读:
    SysTick—系统定时器
    FreeRtos——单任务
    binutils工具集之---objdump
    对连接器的思考
    数组和指针并不相同
    typedef可以成为你的朋友
    gcc,一个神奇的编译器
    FreeRtos——移植
    Makefile 13——理解make的解析行为
    Makefile 12——改善编译效率
  • 原文地址:https://www.cnblogs.com/wt645631686/p/8400367.html
Copyright © 2011-2022 走看看