---
title: "PHP5用装饰模式和工厂模式构造支持Memory Cache的数据库连接类(转) "
author: "yd514"
date: "2012-09-28T16:46:20Z"
tags: []
categories: ["编程语言"]
slug: "php5-memory-cache"
draft: false
lastmod: "2012-09-28T16:46:20Z"
id: 1688141
url: "https://yd514.iteye.com/blog/1688141"
---

转自：http://blog.csdn.net/heiyilvzhe/article/details/5979730

 

需求

1\. 为数据库连接类读数据增加缓存处理，缓存方式可以为文件、Memory Cache

先只对Memory Cache实现

2\. 对现有代码不进行大的改动，方便移植

3\. 数据库连接类可扩充其他功能。

 

客户端调用

以前的方法  
$result = $db\_bbs-&gt;query\_memcache($sql\_str);  
if(!$result) {  
 $result = $db\_bbs-&gt;get\_results($sql\_str);  
 }

现在的只要一行$db\_bbs-&gt;get\_results($sql\_str)。

如果写个文件缓存类的实现，生成文件缓存也像操作数据库一样都用$db\_bbs-&gt;get\_results($sql\_str);  
就是说操作memory cache、文件和真正的数据库没区别，对于调用的程序是透明的。  
使用装饰模式可以将对memory cache、和文件的操作独立出来。

 

 

 

//----------------------------------------我是分割线-------------------------------------------------

 

 

旧的数据库连接类和支持缓存的连接类都实现以下接口

//存储查询写入接口  
interface interface\_DB {  
    public function get\_results($sql, $oMethod = 'A');  
    public function query($sql);  
    public function get\_row($sql , $oMethod = 'A');  
    public function get\_var($sql);  
}

支持不同缓存的连接类可以对get\_results等方法进行各自的实现。

 

 

//----------------------------------------我是分割线-------------------------------------------------

 

 

数据库连接类使用工厂模式构造

下面是具体代码

&lt;?php  
require\_once(DBSTORE."DB\_Base.php");  
class StoreFactory{  
  static function create($db,$classname="") {  
        if(!$classname){  
            return $db;  
        }          
        if (!class\_exists($classname)) {  
            if(include\_once(DBSTORE.$classname.'.php')){  
                return new $classname($db);  
            }else{  
                throw new Exception ($classname .'file not found');  
            }  
        }

          
    }  
}  
?&gt;

 

//----------------------------------------我是分割线-------------------------------------------------

 

支持缓存的数据库连接类

构造函数

    public function \_\_construct(DB\_Base $db){     #初始化  
        $this-&gt;MEM\_PRE\_KEY = $\_SERVER\['SERVER\_NAME'];  
        $this-&gt;db = $db;  
        $this-&gt;mem = new Memcache;  
          
        foreach ($this-&gt;IP as $key=&gt;$value)  
        {  
            $this-&gt;mem-&gt;addServer($value,11211,false);  
        }  
    }

get\_results 实现方法

    public function get\_results($sql,$oMethod="A"){  
        if (preg\_match('/(^select)/sim', $sql)) {  
            $this-&gt;content = $this-&gt;get\_content($sql);  
            if ($this-&gt;content){  
                $this-&gt;content =unserialize($this-&gt;content);  
            }

            if(!$this-&gt;content) {  
                $this-&gt;content = $this-&gt;db-&gt;get\_results($sql,$oMethod);  
                if ($this-&gt;content){  
                    $this-&gt;set\_content($sql,serialize($this-&gt;content),$this-&gt;limit\_time);  
                }

            }}else{  
                $this-&gt;get\_results\_nocache($sql,$oMethod);  
            }  
            return $this-&gt;content;

    }

 

没有缓存或者缓存过期时调用的方法

    protected  function get\_results\_nocache($sql,$oMethod){  
        $this-&gt;content = $this-&gt;db-&gt;get\_results($sql,$oMethod);  
        return $this-&gt;content;  
    }

 

 

 

//----------------------------------------我是分割线-------------------------------------------------

 

&lt;?php

define('DBSTORE',"D:/projects/dp/decorator/store/");  
require\_once(DBSTORE."class\_storefactory.php");

$db = StoreFactory::create($DB\_localhost,"MemoryStore");  
$db-&gt;limit\_time=10;  
$r\_old = $DB\_localhost-&gt;get\_results("select phraseid,varname,text from phrase phraseid limit 0,1#yiduo ");  
$r = $db-&gt;get\_results("select phraseid,varname,text from phrase phraseid limit 0,1#yiduo ");

if($r\_old==$r) {  
 print\_r("OK");  
}

?&gt;

 

 

 

//----------------------------------------我是分割线-------------------------------------------------

 

利用装饰模式可以为数据库连接类扩展功能

如果你写个数据库日志类DB\_LOG

可以这样建一个对象  
$db = StoreFactory::create($DB\_MemoryStore,"DB\_LOG");

那$db 类就有了数据库日志记录功能，同时还有memory cache的功能

数据库日志记录功能本身不和DB\_MemoryStore类耦合，DB\_MemoryStore类的代码不会特别庞大