基于文本的简易k->v数据库改进版

本文介绍了一个基于文本的简易k-v数据库改进版,适用于小规模存储和替代redis、新浪SAEKVDB等。重点包括改进中文乱码问题、数据库结构优化以及API使用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php


/**
*       基于文本的简易k->v数据库改进版
*       小规模存储k->v的数据库,数据库结构为JSON,可以在小项目中代替redis,新浪SAE KVDB等
*       @author cemike@126.com 2015/07/04
*       基于以下代码改进,致谢!
*       参考:基于文本方式的KVDB - 开源中国社区 http://my.oschina.net/suconghou/blog/195755
*       修正中文乱码问题:
*       1. 所有页面都用utf-8编码存储(可以用editplus进行可靠的文档编码转换)
*       2. 页面开头加上<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
*       3. 对于所有中文字符(仅仅中文,数字英文不要编码)$v存入JSON数据结构及磁盘文件前都要进行urlencode($v)编码转换,
*          JSON数据结构及磁盘文件中的数据类似于{"init_time":1436070089,"msg.1.keyName1":"%E5%A7%93%E5%90%8D"},
*          否则读取数据并进行JSON解析时$dbarr=json_decode($contents);返回结果null
*       4. 查找出来的数据$v如果在前台页面显示必须相应解码urldecode($v)
*       
*       kvdb API 
* set($key,$value);
*       sets($arr);//一次设置多个
*       get($key);
*       gets($key); 以x开头或者所有
*       del($key);
*       flush();//删除所有
*       like($key);//包含x的
*       增加:
*       function pkrget($key=null, $count) //兼容SAE KVDB,调用like($key)方法,并忽略了$count参数
*       function replace($key,$value)//兼容SAE KVDB,调用set($key,$value)方法
*       function delete($key) //兼容SAE KVDB,调用del($key)方法
*       初始化参数  tmp--存储在系统临时目录(windows通常为c:\windows\tmp\LVDB.tmp)
*                   为空加载默认(apache通常为www\htdocs\kvdb.txt)
*                   其他字符在/www或者项目当前目录生成文件
*       注意:1. kvdb对象销毁时数据会自动存储到文件$dbfile(参考function __destruct())
*             2. 如果要强制中途写入数据到磁盘,可调用function change($file=null)
*             3. 清空数据库function flush(),但不会立即存入磁盘
*             
*/
class kvdb 
{
    private static $dbfile='kvdb.txt';///默认数据库
    private static $dbarr;
 
    function __construct($file=null)
    {
        self::init($file);
    }
 
    ///从文本读入内存
    private static function read()
    {
        $contents=file_get_contents(self::$dbfile);
        //var_dump($contents);
        //$mb=mb_convert_encoding($contents, "GBK", "UTF-8");
//var_dump($mb);
        //$encoded=urlencode($contents);
//var_dump($encoded);
$dbarr=json_decode($contents);

//$dbarr=json_decode(mb_convert_encoding(file_get_contents(self::$dbfile), "GBK", "UTF-8"));
//echo "read: ";
//var_dump(mb_convert_encoding(file_get_contents(self::$dbfile), "GBK", "UTF-8"));
//var_dump($dbarr);
        return $dbarr; 
    }
    //存入文本
    private static function write($dbarr)
    {
//$dbarr=urldecode();
$dbarr=json_encode($dbarr);
//var_dump($dbarr);
        return file_put_contents(self::$dbfile,$dbarr);
    }
    /*
修正创建多个实例时$dnfile路径错误。
self::$dbfile=$_SERVER['DOCUMENT_ROOT'].self::$dbfile;
改为:
self::$dbfile=$_SERVER['DOCUMENT_ROOT'].'kvdb.db';
去掉了中间路径/app/s/
*/
private static function init($file=null)
    {
        if($file==null)//加载默认
        {
            //self::$dbfile=$_SERVER['DOCUMENT_ROOT'].self::$dbfile;
self::$dbfile=$_SERVER['DOCUMENT_ROOT'].'/kvdb.txt';//'/app/s/'.
        }
        else if($file=='tmp')
        {   
            self::$dbfile=sys_get_temp_dir().'/KVDB.tmp';
        }
        else //指定文件名
        {
            self::$dbfile=$_SERVER['DOCUMENT_ROOT'].'/'.$file;//'/app/s/'.
        }
        if(!file_exists(self::$dbfile))
        {
            $init=array('init_time'=>time());
            file_put_contents(self::$dbfile,json_encode($init));
        }/**/
        self::$dbarr=self::read();
    }
    function get($key)
    {
        return isset(self::$dbarr->$key)?self::$dbarr->$key:null;
    }
    function gets($key=null)
    {
        if(empty(self::$dbarr))
        {
            $this->flush();
        }
        foreach (self::$dbarr as $k=> $v)
        {
            if(substr($k,0,strlen($key))==$key)
            {
                $res[$k]=$v;
            }
        }
        return isset($res)?$res:null;
 
    }
    function set($key,$value)
    {
        if(empty(self::$dbarr))
        {
            $this->flush();
        }
        self::$dbarr->$key=$value;
    }
    function replace($key,$value)
    {
if(self::get($key)!=null)self::set($key, $value);
}
    function sets($arr)
    {
        if(empty(self::$dbarr))
        {
            $this->flush();
        }
        foreach ($arr as $key => $value)
        {
            self::$dbarr->$key=$value;
        }
    }
function delete($key)
    {
return self::del($key);
}
    function del($key)
    {
        if(isset(self::$dbarr->$key))
        {
            unset(self::$dbarr->$key);   
        }
        else
        {
            return true;
        }
    }
    function flush()
    {
        self::$dbarr=(object)array('init_time'=>time());
    }
 
    function like($key=null)
    {
        if(empty(self::$dbarr))
        {
            $this->flush();
        }
        foreach (self::$dbarr as $k => $v)
        {
            if (stripos($k,$key)!==false)
            {
                $res[$k]=$v;
            }
        }
        return isset($res)?$res:null;
 
    }
    function pkrget($key=null, $count)
    {
return self::like($key);
}
function change($file=null)
    {
        if($file==null)
        {
            self::$dbfile='kvdb.db';
        }
        self::write(self::$dbarr);
        self::init($file);
 
    }
    function __destruct()
    {
//echo '<br><span>Write kvdb to json file: '.self::$dbfile.'</span><br>';
/*foreach ( self::$dbarr as $key => $value ) {  
self::$dbarr[$key] = urlencode ( $value );  
}*/ 
return self::write(self::$dbarr);
 
    }
 
}
 
/*

$db=new kvdb('kvdb.txt');
$db->set('用户名','张三');
$db->set('user_1','111');
$db->set('user_2','2222');
$db->set('user_3','3333');
$db->set('sua_3','wsss');
 
$a=$db->gets('user');
$b=$db->like('a');
var_dump($a);
var_dump($b);
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值