适配器模式:即将截然不同的函数接口封装成统一的接口API
例如 MYSQL的数据库扩展操作 mysql,mysqli,pdo三种,可以用适配器模式统一成一致.
类似的场景还有cache操作,例如 redis,memcached,mongodb,apc等不同的缓存函数,统一成一致

<?php

namespace Lib;

interface Database
{
    function connect($host,$name,$pass,$db);
    function query($sql);
    function close();
}
<?php

namespace Lib\Database;

class Mysql implements \Lib\Database{
   public function connect($host,$name,$pass,$db)
   {

   }
   public function query($sql)
   {

   }

   public function close()
   {

   }
}
<?php

namespace Lib\Database;

class Mysqli implements \Lib\Database{
    private $conn;
    public function connect($host,$user,$pass,$db)
    {
        $this->conn = mysqli_connect($host,$user,$pass,$db);
    }
    public function query($sql)
    {
        return mysqli_query($this->conn ,$sql);
    }


    public function close()
    {
        mysqli_close($this->conn);
    }
}
$db = new \Lib\Database\Mysqli();
print_r($db);

results matching ""

    No results matching ""

    results matching ""

      No results matching ""