zoukankan      html  css  js  c++  java
  • php设计模式--适配器模式

    适配器模式主要是将不同的函数接口封装成统一的API,下面就拿php链接操作数据库的三种方式来说明适配器模式mysql,mysqli,PDO 。类似的还有cache,主要是memcache,redis,file等。

    以数据库操作为例直接上代码:

    首先声明一个接口:

    约定适配器的行为,约定好之后分别去创建适配器实例。

    <?php
    interface Indatabase
    {
    	function connect($host,$user,$password,$dbname);
    	function query($sql);
    	function close();
    }
    

     

    mysql:

    <?php
    
    class mysql implements Indatabase
    {
    	protected $conn;
    	function connect($host,$user,$password,$dbname)
    	{
    		$conn = mysql_connect($host,$user,$password);
    		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);
    	}
    }
    

    mysqli:

    <?php
    class mysqli implements Indatabase
    {
    	protected $conn;
    	function connect($host,$user,$password,$dbname)
    	{
    		$conn = mysqli_connect($host,$user,$password,$dbname);
    		$this->conn = $conn;
    	}
    
    	function query($sql)
    	{
    		$res = mysqli_query($this->conn,$sql);
    		return $res;
    	}
    
    	function close()
    	{
    		mysqli_close($this->conn);
    	}
    }
    

    PDO:

    <?php
    class PDO implements Indatabase
    {
    	function connect($host,$user,$password,$dbname)
    	{
    		$conn = new PDO("mysql:host=$host;dbname=$dbname",$user,$password);
    		$this->conn = $conn;
    	}
    
    	function query($sql)
    	{
    		return $this->conn->query($sql);
    	}
    
    	function close()
    	{
    		unset($this->conn);
    	}
    }
    

    $db = new mysql();

    $db->connect('127.0.0.1','root','123456');

    $db->query($sql);

    $db->close();

    之后我们就能随意在这三种数据库操作类任意切换,在一个框架中要支持所有的环境,这样在服务器上用户可以通过选择来使用mysql操作类,这样用户就可以通过此功能来完成适配,这就是适配器模式。

  • 相关阅读:
    RAC安装时,报The specified nodes are not clusterable 的解决方法
    Unix sar 命令
    Linux 修改 IP地址 和 网关
    Oracle ASM 详解
    RAC安装时需要执行4个脚本及意义
    RAC 的一些概念性和原理性的知识
    Oracle 10g RAC 启动与关闭
    Oracle RAC 修改 IP 地址
    Linux 时间同步配置
    RAC安装时,报The specified nodes are not clusterable 的解决方法
  • 原文地址:https://www.cnblogs.com/phpworld/p/7445032.html
Copyright © 2011-2022 走看看