tmarois/filebase

此包已被放弃且不再维护。未建议任何替代包。
关于此包最新版本(v1.0.24)没有可用的许可证信息。

一个简单但强大的平面文件数据库存储。

安装次数: 30,154

依赖者: 10

建议者: 1

安全性: 0

星标: 279

关注者: 24

分支: 49

开放问题: 20

类型:package

v1.0.24 2019-02-24 22:55 UTC

README

Filebase

Build Status Coverage Status

加入 Discord – 用于支持、更新和协作。

一个简单但强大的平面文件数据库存储。无需 MySQL 或昂贵的 SQL 服务器,实际上,您只需要当前站点或应用程序的设置。所有数据库条目都存储在文件中(格式化成您喜欢的样子)。

您甚至可以在不使用 API 的情况下直接修改文件中的原始数据。更好的是,您可以将其所有文件放入 版本控制 中,并将其传递给团队,而不必担心不一致的 SQL 数据库。

这难道不很酷吗?

使用 Filebase,您可以完全掌控。按照您想要的任何方式设计数据结构。像在 PHP 中一样使用数组和对象。使用版本控制更新和与他人共享您的数据。只需记住,升级您的 Web/apache 服务器比数据库服务器要少得多。

支持 PHP 5.6PHP 7+

功能

Filebase 设计简单,但功能足够高级。

安装

使用 Composer 安装包。

运行 composer require tmarois/filebase:^1.0

如果您不想使用 composer,下载文件,并在您的应用程序中包含它,它没有依赖项,您只需将其与未来的版本保持更新即可。

用法

// setting the access and configration to your database
$database = new \Filebase\Database([
    'dir' => 'path/to/database/dir'
]);

// in this example, you would search an exact user name
// it would technically be stored as user_name.json in the directories
// if user_name.json doesn't exists get will return new empty Document
$item = $database->get('kingslayer');

// display property values
echo $item->first_name;
echo $item->last_name;
echo $item->email;

// change existing or add new properties
$item->email = 'example@example.com';
$item->tags  = ['php','developer','html5'];

// need to save? thats easy!
$item->save();


// check if a record exists and do something if it does or does not
if ($database->has('kingslayer'))
{
    // do some action
}

// Need to find all the users that have a tag for "php" ?
$users = $db->where('tags','IN','php')->results();

// Need to search for all the users who use @yahoo.com email addresses?
$users = $db->where('email','LIKE','@yahoo.com')->results();

(1) 配置选项

当定义数据库时,配置是 必需的。选项是 可选的,因为它们有默认值。

使用示例(所有选项)

$db = new \Filebase\Database([
    'dir'            => 'path/to/database/dir',
    'backupLocation' => 'path/to/database/backup/dir',
    'format'         => \Filebase\Format\Json::class,
    'cache'          => true,
    'cache_expires'  => 1800,
    'pretty'         => true,
    'safe_filename'  => true,
    'read_only'      => false,
    'validate' => [
        'name'   => [
            'valid.type' => 'string',
            'valid.required' => true
        ]
    ]
]);
名称 类型 默认值 描述
dir 字符串 当前目录 存储数据库文件的目录。
backupLocation 字符串 当前目录(/backups 备份 zip 文件将存储的目录。
format 对象 \Filebase\Format\Json 用于编码/解码数据的格式类
validate 数组 请参阅 验证规则 以获取更多详细信息
cache 布尔值 true 查询 结果存储到缓存中,以便更快地加载。
cache_expire 整数 1800 缓存将持续多长时间(以秒为单位)
漂亮的 布尔值 true 存储数据以便人类可读?格式化输出
安全文件名 布尔值 true 自动将文件名转换为有效名称(添加:1.0.13)
只读 布尔值 false 防止数据库创建/修改文件或目录(添加:1.0.14)

(2)格式化

格式类定义了数据库文件内数据的编码和解码。

您可以在配置中编写自己的格式类或更改现有的格式类。类中的方法必须是static,并且类必须实现\Filebase\Format\FormatInterface

默认格式类:JSON

\Filebase\Format\Json::class

其他格式类:Yaml

\Filebase\Format\Yaml::class

(3)GET(及方法)

在加载完数据库配置后,您可以使用get()方法检索单个数据文档。

如果文档不存在,它将为您创建一个空对象以便存储数据。然后您可以调用save()方法,它将创建文档(或更新现有文档)。

// my user id
$userId = '92832711';

// get the user information by id
$item = $db->get($userId);

get()返回\Filebase\Document对象,并具有您可以调用的自己的方法。

方法 详细信息
save() 保存当前状态下的文档
delete() 删除当前文档(不可撤销)
toArray() 文档中的项目数组
getId() 文档 ID
createdAt() 文档创建时间(默认 Y-m-d H:i:s)
updatedAt() 文档更新时间(默认 Y-m-d H:i:s)
field() 您也可以使用.点分隔符来从嵌套数组中查找值
isCache() (true/false)如果当前文档是从缓存中加载的
filter() 请参阅自定义过滤器

示例

// get the timestamp when the user was created
echo $db->get($userId)->createdAt();

// grabbing a specific field "tags" within the user
// in this case, tags might come back as an array ["php","html","javascript"]
$user_tags = $db->get($userId)->field('tags');

// or if "tags" is nested in the user data, such as about[tags]
$user_tags = $db->get($userId)->field('about.tags');

// and of course you can do this as well for getting "tags"
$user = $db->get($userId);
$user_tags = $user->tags;
$user_tags = $user->about['tags'];

(4)创建 | 更新 | 删除

如上例所示,它非常简单。使用$item->save(),默认情况下,save()方法将创建或更新现有文档。它将通过createdAtupdatedAt记录所有更改。如果您想要替换单个文档内的所有数据,请通过save($data)方法传递新数据,否则不要传递任何数据,以便允许它保存当前实例。

// SAVE or CREATE
// this will save the current data and any changed variables
// but it will leave existing variables that you did not modify unchanged.
// This will also create a document if none exist.
$item->title = 'My Document';
$item->save()

// This will replace all data within the document
// Allows you to reset the document and put in fresh data
// Ignoring any above changes or changes to variables, since
// This sets its own within the save method.
$item->save([
    'title' => 'My Document'
]);

// DELETE
// This will delete the current document
// This action can not be undone.
$item->delete();

(5)数据库方法

$db = new \Filebase\Database($config);

以下是您可以在数据库类上使用的方法列表。

方法 详细信息
version() 当前 Filebase 库版本
get($id) 请参阅get()
has($id) 检查记录是否存在,返回 true/false
findAll() 返回数据库中的所有文档
count() 数据库中的文档数量
flush(true) 删除所有文档。
flushCache() 清除所有缓存
truncate() 删除所有文档。与flush(true)同义
query() 请参阅查询
backup() 请参阅备份

示例

$users = new \Filebase\Database([
    'dir' => '/storage/users',
]);

// displays number of users in the database
echo $users->count();


// Find All Users and display their email addresses

$results = $users->findAll();
foreach($results as $user)
{
    echo $user->email;

    // you can also run GET methods on each user (document found)
    // Displays when the user was created.
    echo $user->createdAt();
}


// deletes all users in the database
// this action CAN NOT be undone (be warned)
$users->flush(true);

(6)验证 (可选)

在调用save()方法时,将检查文档的验证规则(如果设置)。只有这些规则通过,文档才能保存。

$db = new \Filebase\Database([
    'dir' => '/path/to/database/dir',
    'validate' => [
        'name'   => [
            'valid.type' => 'string',
            'valid.required' => true
        ],
        'description' => [
            'valid.type' => 'string',
            'valid.required' => false
        ],
        'emails' => [
            'valid.type'     => 'array',
            'valid.required' => true
        ],
        'config' => [
            'settings' => [
                'valid.type'     => 'array',
                'valid.required' => true
            ]
        ]
    ]
]);

在上面的示例中,namedescriptionemailsconfig数组键将替换为您自己的键,这些键与您的数据匹配。注意,config有一个嵌套数组settings,是的,您可以嵌套验证。

验证规则

名称 允许的值 描述
valid.type 字符串str整数int数组 检查属性是否为当前类型
valid.required truefalse 检查属性是否在文档中

(7) 自定义过滤器

注意:自定义过滤器仅对单个文档运行

项目过滤器允许您自定义结果,并在同一文档中进行简单的查询。如果您在一个文档中有一个项目数组,这些过滤器非常棒。比如说,您将“users”作为数组存储在users.json中,然后您可以创建一个过滤器来显示所有具有特定标签或字段匹配特定值的用户。

此示例将输出所有被封锁用户的电子邮件。

// Use [data] for all items within the document
// But be sure that each array item uses the same format (otherwise except isset errors)

$users = $db->get('users')->filter('data','blocked',function($item, $status) {
    return (($item['status']==$status) ? $item['email'] : false);
});

// Nested Arrays?
// This uses NESTED properties. If the users array was stored as an array inside [list]
// You can also use `.` dot delimiter to get arrays from nested arrays

$users = $db->get('users')->filter('list.users','blocked',function($item, $status) {
    return (($item['status']==$status) ? $item['email'] : false);
});

(8) 查询

查询允许您搜索多个文档,并仅返回符合您标准的文档。

如果启用缓存,查询将使用findAll(),然后在下一次运行时缓存结果。

注意:您不再需要调用query(),您现在可以直接在数据库类上调用查询方法。

// Simple (equal to) Query
// return all the users that are blocked.
$users = $db->where(['status' => 'blocked'])->results();

// Stackable WHERE clauses
// return all the users who are blocked,
// AND have "php" within the tag array
$users = $db->where('status','=','blocked')
            ->andWhere('tag','IN','php')
            ->results();

// You can also use `.` dot delimiter to use on nested keys
$users = $db->where('status.language.english','=','blocked')->results();

// Limit Example: Same query as above, except we only want to limit the results to 10
$users = $db->where('status.language.english','=','blocked')->limit(10)->results();



// Query LIKE Example: how about find all users that have a gmail account?
$usersWithGmail = $db->where('email','LIKE','@gmail.com')->results();

// OrderBy Example: From the above query, what if you want to order the results by nested array
$usersWithGmail = $db->where('email','LIKE','@gmail.com')
                     ->orderBy('profile.name', 'ASC')
                     ->results();

// or just order the results by email address
$usersWithGmail = $db->where('email','LIKE','@gmail.com')
                     ->orderBy('email', 'ASC')
                     ->results();

// OrderBy can be applied multiple times to perform a multi-sort
$usersWithGmail = $db->query()
                    ->where('email','LIKE','@gmail.com')
                    ->orderBy('last_name', 'ASC')
                    ->orderBy('email', 'ASC')
                    ->results();

// this will return the first user in the list based on ascending order of user name.
$user = $db->orderBy('name','ASC')->first();
// print out the user name
echo $user['name'];

// You can also order multiple columns as such (stacking)
$orderMultiples = $db->orderBy('field1','ASC')
                     ->orderBy('field2','DESC')
                     ->results();

// What about regex search? Finds emails within a field
$users = $db->where('email','REGEX','/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i')->results();

// Find all users that have gmail addresses and only returning their name and age fields (excluding the rest)
$users = $db->select('name,age')->where('email','LIKE','@gmail.com')->results();

// Instead of returning users, how about just count how many users are found.
$totalUsers = $db->where('email','LIKE','@gmail.com')->count();


// You can delete all documents that match the query (BULK DELETE)
$db->where('name','LIKE','john')->delete();

// Delete all items that match query and match custom filter
$db->where('name','LIKE','john')->delete(function($item){
    return ($item->name == 'John' && $item->email == 'some@mail.com');
});


// GLOBAL VARIABLES

// ability to sort the results by created at or updated at times
$documents = $db->orderBy('__created_at', 'DESC')->results();
$documents = $db->orderBy('__updated_at', 'DESC')->results();

// search for items that match the (internal) id
$documents = $db->where('__id', 'IN', ['id1', 'id2'])->results();

要运行查询,请使用results()或如果您只想返回第一个项目,请使用first()

查询方法

这些方法是可选的,并且是可堆叠的

方法 参数 详细信息
select() 数组字符串(逗号分隔) 仅选择您希望返回的字段(对于每个文档),用法:field1,field2
where() 混合 数组用于简单的“等于”或where($field, $operator, $value)
andWhere() 混合 where(),使用逻辑AND
orWhere() 混合 where(),此操作使用逻辑OR
limit() int限制,int偏移 要返回的文档数量和偏移量
orderBy() 字段排序顺序 按特定字段和按ASCDESC排序文档
delete() 闭包 能够批量删除所有匹配的项目

以下方法执行查询并返回结果(不要同时使用它们)

方法 详细信息
count() 计数并返回结果中的文档数量。
first() 仅返回结果中的第一个文档。
last() 仅返回结果中的最后一个文档。
results() 这将返回找到的所有文档及其数据作为数组。传递参数false将与resultDocuments()相同(返回完整的文档对象)
resultDocuments() 这将返回找到的所有文档及其数据作为文档对象,或者您可以执行results(false),这是别名。

比较运算符

名称 详细信息
=== 相等
=== 严格相等
!= 不等于
NOT 不等于(与!=相同)
!== 严格不等于
> 大于
>= 大于等于
< 小于
<= 小于等于
IN 检查值是否在数组中
LIKE 不区分大小写的正则表达式搜索
NOT LIKE 不区分大小写的正则表达式搜索(相反)
REGEX 正则表达式搜索

(9) 缓存

如果启用缓存,它将自动将查询结果存储在数据库目录内的子目录中。

缓存的查询仅在特定保存的缓存小于过期时间时才会使用,否则它将使用实时数据并自动替换下一次使用时现有的缓存。

(10) 数据库备份

默认情况下,您可以使用$db->backup()->create()备份您的数据库,这将根据您的dir路径创建整个数据库的.zip文件。

方法

这些方法可以在调用backup()时用于您的Database

  • create() 创建数据库备份(在您的备份位置.zip
  • clean() 清除所有现有备份(在您的备份位置中的.zip文件)
  • find() 返回所有现有备份的 array(数组键为 time() 创建备份时的时刻)
  • rollback() 恢复现有备份(最新可用),替换现有数据库 dir

示例

// invoke your database
$database = new \Filebase\Database([
    'dir' => '/storage/users',
    'backupLocation' => '/storage/backup',
]);

// create a new backup of your database
// will look something like /storage/backup/1504631092.zip
$database->backup()->create();

// delete all existing backups
$database->backup()->clean();

// get a list of all existing backups (organized from new to old)
$backups = $database->backup()->find();

// restore an existing backup (latest backup available)
$database->backup()->rollback();

为什么选择Filebase?

Filebase是为了帮助管理简单数据存储而构建的,无需处理重型数据库引擎的麻烦。Filebase的概念是提供非常直观的API方法,并使开发人员轻松维护和管理(即使是大规模)。

受到FlywheelFlinetone的启发。

版本如何工作

版本格式如下:主.次.补丁

  • 主:完全使用新代码库重写的版本。
  • 次:引入新功能/变更,可能会破坏兼容性。
  • 补丁:引入新功能/修复,不会破坏兼容性。

Filebase会尽力在可能的情况下实现向后兼容。

Filebase的网站和用户

如果您正在使用Filebase – 请提交拉取请求,我们将在此处添加您的项目。

贡献

任何人都可以为Filebase做出贡献。请在发现意外情况时提交问题,或发送拉取请求进行改进。

许可证

Filebase是开源软件,许可协议为MIT许可证