commandstring / jsondb
更简单的方式来使用JSON作为数据库
v1.1.1
2023-02-05 17:28 UTC
Requires
- commandstring/utils: ^1.4
README
一个类似于MySQL结构的完全可定制的JSON数据库系统
创建数据库
<?php use CommandString\JsonDb\Structure\Database; use CommandString\JsonDb\Structure\Table; class YourDatabase extends Database { protected static array $tableClasses = []; }
创建一个扩展 CommandString\JsonDb\Structure\Database
的类,并添加上述属性。我们稍后会回到它
创建表格
<?php use CommandString\JsonDb\Structure\Table; class YourTable extends Table { protected static string $name = "yourtable"; protected static string $fileLocation = __DIR__."/yourtable.json"; protected static array $columns = []; }
创建一个扩展 CommandString\JsonDb\Structure\Table
的类,就像上面那样。第一个属性是表将被如何识别,第二个是表的JSON将存储/检索的位置,稍后我还会回到列属性。然而,对于数据库类中的 tableClasses 属性,您将想将其添加如下...
// ... protected static array $tableClasses = [YourDatabase::class]; // ...
并将您创建的任何未来表追加到这个属性中
创建列
use CommandString\JsonDb\Structure\Column; use CommandString\JsonDb\Structure\DataTypes; class YourColumn extends Column { protected static DataTypes $type = DataTypes::STRING; protected static string $name = "yourcolumn"; protected static array $enumValues = []; protected static string|int|float|null $default; protected static bool $nullable = false; protected static bool $unique = false; }
创建一个扩展 CommandString\JsonDb\Structure\Column
的类,然后添加上述属性。可用的数据类型有字符串、整数、浮点数和枚举。如果类型是枚举,确保将此列可以包含在枚举值数组中的值添加进去。
特殊说明
- 我建议在您的类中添加魔术方法和公共常量,以利用编码时的代码智能提示,请查看 TestDb 作为示例
- 列和表名将始终小写,因此我建议默认将它们设置为小写,以防止任何混淆。
创建行
$db = new YourDatabase; // you can also pass JSON encoder flags into the constructor $row = $db->yourtable->newRow(); $row->setColumn($db->yourtable::COLUMN_NAME, "<value>") // you can pass a string for the column name but I recommend having constants has mentioned earlier $row = $row->store(); // returns that same row but this is associated to specific point in the JSON file
获取行
/** * @var Row[] */ $results = $db->yourtable->newQuery()->whereAnd($db->yourtable::COLUMN_NAME, Operators::EQUAL_TO, "<value>")->execute();
更新行
$row = $results[0]; $row->setColumn($db->yourtable::COLUMN_NAME, "<new value>"); $row->store(); // updated the row