meyersm/simple-datastore

该软件包最新版本(0.5.2)没有提供许可证信息。

一个PHP库,仅使用本地文件系统在会话之间存储对象

0.5.2 2014-01-20 20:05 UTC

This package is not auto-updated.

Last update: 2024-09-24 01:46:13 UTC


README

Build Status

一个PHP库,仅使用本地文件系统在会话之间存储对象。

对象可以以json或序列化格式存储,并以只读模式或读写模式打开,读写模式会锁定数据存储以防止覆盖或竞争条件。

simpleDatastore 的良好用途

  • 需要在脚本/会话之间保留数据,但数据库过于庞大或不可行
  • 需要与另一个非PHP脚本/代码共享数据,而json是最方便的
  • 作为数据库连接失败时的备选方案来保留数据。

该库不应用于任何高流量和高并发写入的应用程序中的数据库替代品,因为写入时文件被锁定,任何其他想要写入的线程/脚本都必须等待锁定,从而导致速度减慢。

安装

使用composer安装,将以下内容添加到您的composer.json文件中

	"require": {
        "meyersm/simple-datastore":">=0.5.2"
	},

然后运行 composer update 并将以下内容添加到您的代码中,

use meyersm\simpleDatastore;

或者您可以直接下载simpleDatastore.php文件并将其添加到您的代码中,

require('simpleDatastore.php');
use meyersm\simpleDatastore;

用法

创建一个新的数据存储

$datastore = new simpleDatastore("datastore-name");

然后您可以从添加数据开始,并将其保存到新的数据存储中

$datastore->fish_hooks = 50;
$datastore->fish_names = array("bob","archibold","thomas");
$datastore->enable_fish= true;
$datastore['array_access'] = "yup";
$datastore[] = "new array entry";
$datastore->save();

数据存储在文件关闭之前仍会锁定该文件,此时另一个脚本可以打开并读取数据

$datastore->close();
//You can also call $datastore->save(true) to save then close in 1 line
$NEWdatastore = new simpleDatastore("datastore-name");
print $NEWdatastore->fish_hooks; //50
print $NEWdatastore['fish_names'][0] //bob

如果您想删除数据存储文件,请使用destroy函数

$datastore->destroy();

当尝试打开已被锁定的数据存储时,库将重试一段时间后出错。如果您想在数据存储被锁定时访问它,您可以以只读模式打开它

$datastore = new simpleDatastore("myDatastore",true);

如果您想将PHP类以序列化对象的形式而不是json格式存储,请在打开数据存储时将序列化标志设置为true

$datastore = new simpleDatastore("myDatastore",false,true);
$datastore->complexClass = $CC;
$datastore->otherDatastore = $someOtherDatastore //You can even serialize other simpleDatastore objects if you like. 

默认情况下,库将所有数据存储及其锁定文件存储在名为“datastore”的子目录中。它还在发生错误时抛出异常,如果您想更改这些默认值,可以这样做。

$datastore = new simpleDatastore("teststore",false,false,"anotherDirectory"); //Different directory for datastore files
$teamB = new simpleDatastore(); //If you are going to change the error mode, you may want to wait to load the file instead of doing so at instantiation

$teamB->error_mode = simpleDatastore::$ERROR_MODE_SILENT; //Fails silently, will leave datastore null if error on read
$teamB->error_mode = simpleDatastore::$ERROR_MODE_DIE; //Dies on fatal error, ending script execution
$teamB->error_mode = simpleDatastore::$ERROR_MODE_EXCEPTION; //Default, throws exceptions on fatal errors
$teamB->open("teststore");

要更改库处理锁定数据存储文件的方式,请使用setLockConfig函数。再次提醒,如果您这样做,请像上面的示例那样延迟打开数据存储文件

/**
* @param int $secondsBetweenLockAttempts Seconds to wait between lock attempts
* @param int $lockAttempts Number of tries to try and lock datastore
*/
public function setLockConfig($secondsBetweenLockAttempts=1,$lockAttempts=20)

有关如何使用该库的更多示例,请查看单元测试

单元测试