利用php的序列化和反序列化来做简单的数据本地存储

时间:2024-06-16 22:34:26

利用php的序列化和反序列化来做简单的数据本地存储

如下程序可以做为一个工具类

      /**
* 利用php的序列化和反序列化来做简单的数据本地存储
*/
class objectdb
{ private static $db; //成功返回 objectdb 对象,不需要在外面使用new
//目录需要写文件的权限
public function defaultdb($dbname='./default.db')
{
self::$db = $dbname;
if(file_exists($dbname))
{
return new objectdb();
} $ret=file_put_contents($dbname,serialize(array()));
if ($ret > 0) {
return new objectdb();
}
return false;
} //添加数据key,value 或更新
public function setValueForKey($key,$value)
{
$arrdata = $this->getDBarray();
$arrdata[$key] = $value;
return $this->setDBarray($arrdata);
} //删除指定key的数据
public function removeValueForKey($key)
{
$arrdata = $this->getDBarray();
unset($arr[$key]);
} //获取指定key的数据
public function getValueForKey($key)
{
$arrdata = $this->getDBarray();
return $arrdata[$key];
} //获取所有的数据
public function getAll()
{
$arrdata = $this->getDBarray();
return $arrdata;
} //获取所有的key
public function getAllKey()
{
$arrdata = $this->getDBarray();
return array_keys($arrdata);
} //清空db数据
public function cleardb()
{
$ret=file_put_contents(self::$db,serialize(array()));
return $ret;
} //private get
private function getDBarray()
{
$rdata=file_get_contents(self::$db);
return unserialize($rdata);
} //private set
private function setDBarray($arr)
{
$ret=file_put_contents(self::$db,serialize($arr));
if ($ret > 0) {
return true;
}else
{
return false;
}
} }

测试代码如下

    //test
$dbhandle = objectdb::defaultdb();
if (!$dbhandle) {
echo "init failure!";
exit();
} echo "start <br>";
var_dump($dbhandle->getAll()); echo "<br>add 1 <br>";
$dbhandle->setValueForKey("baidu","www.baidu.com");
$dbhandle->setValueForKey("qq","www.qq.com");
$dbhandle->setValueForKey("taobao","www.taobao.com");
var_dump($dbhandle->getAll()); echo "<br>mod 1 <br>";
$dbhandle->setValueForKey("baidu","http://www.baidu.com");
var_dump($dbhandle->getAll()); echo "<br>get 1 <br>";
echo $dbhandle->getValueForKey("baidu"); echo "<br>get 1 <br>";
var_dump($dbhandle->getAllKey()); echo "<br>clear 1 <br>";
$dbhandle->cleardb(); echo "<br>get 1 <br>";
var_dump($dbhandle->getAll());