我的问题是关于将文件系统用作数据库来简单保存JSON
个文件。
我想出了以下代码,一点也不完美。我发现使用JSON
文件非常容易存储和提取数据。
我的问题是,该数据库适合于任何大型项目吗?会很快吗?还是使用这种方法的局限性仅仅是与安全相关?
PHP
是否有针对此类情况的内置解决方案?
认识的人对此事的任何投入都会受到赞赏...
class JDB{
public $path;
function JDB( $path = __DIR__.'/jdb/' ){
$this->path = $path;
if( !file_exists($this->path) ) mkdir($this->path);
}
function p($t){
return $this->path.$t.'.json';
}
function get($t){
return json_decode(file_get_contents( $this->p($t) ));
}
function set($t,$c){
return file_put_contents( $this->p($t), json_encode($c,JSON_PRETTY_PRINT) );
}
function create( $t, $d = [] ){
$s = file_put_contents( $this->p($t), json_encode($d) );
return $s;
}
function destroy(){
$files = glob($this->path.'*'); // get all file names present in folder
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete the file
}
}
function delete( $t ){
$s = unlink( $this->p($t) );
return $s;
}
function insert( $t, $d = null ){
if($d) $d['__uid'] = $t.'_'.$this->uid();
$c = $this->get($t);
array_push($c,$d);
$s = $this->set($t,$c);
if($s) return $d['__uid'];
}
function update($t,$conditions,$u){
$c = $this->get($t);
$this->search($c,$conditions,function($object) use (&$c,$u){
foreach ($u as $key => $value) {
$object->$key = $value;
}
});
$this->set($t,$c);
}
function remove($t,$conditions){
$c = $this->get($t);
$this->search($c,$conditions,function($object,$key) use (&$c){
unset($c[$key]);
});
$this->set($t,$c);
}
function search( $c, $conditions = [], $fn ){
$l = count($conditions);
foreach ($c as $key => $object) {
$f = 0;
foreach ($conditions as $k => $v) {
if( property_exists($object,$k) && ($object->$k == $v) ){
$f++;
if( $f==$l ) $fn($object,$key);
}else break;
}
}
}
function select( $t, $conditions = [] ){
$c = $this->get($t);
$r = [];
$this->search($c,$conditions,function($object) use (&$r){
array_push($r,$object);
});
if (count($r) == 0) return false;
if (count($r) == 1) return $r[0];
return $r;
}
function count($t){
$c = $this->get($t);
return count($c);
}
function uid($length = 20) {
$c = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$cl = strlen($c);
$uid = '';
for ($i = 0; $i < $length; $i++) {
$uid .= $c[rand(0, $cl - 1)];
}
return $uid;
}
}
非常简单,这个问题是否有可能...
$db = new JDB();
$db->create('users');
$db->create('pages');
$user_uid = $db->insert('users',[
'name' => 'a',
'password' => 'hello world',
'pages' => []
]);
$user_uid = $db->insert('users',[
'name' => 'b',
'password' => 'hello world',
'pages' => []
]);
$page_uid = $db->insert('pages',[
'name' => 'page 1',
'content' => 'hello world',
'users' => [$user_uid]
]);
$user = $db->select('users',['name' => 'a']);
$page = $db->select('pages',['users' => [$user_uid]]);
$db->update('users',['name' => 'b'],['pages' => [$page->__uid]]);
$db->remove('users',['name' => 'a']);