fly-crud/fly-crud

基于flysystem构建的简单crud系统

v3.0.0 2019-01-24 09:53 UTC

This package is auto-updated.

Last update: 2024-08-25 07:12:27 UTC


README

Scrutinizer Code Quality Build Status

有时你不需要数据库,只需一些存储在yaml/json等文件中的数据来构建网站。

这个库提供了一个简单的方法来管理使用flysystem作为引擎存储在文件中的数据。

安装

该库与PHP >= 7.1兼容,可以通过Composer以fly-crud/fly-crud的方式安装和自动加载。

$ composer require fly-crud/fly-crud

使用示例

use FlyCrud\Directory;
use FlyCrud\Formats\Json;

//Create a repository to store the data as json
$repo = Directory::make('/path/to/files', new Json());

//Create a new document
$document = new Document([
    'title' => 'Title post',
    'intro' => 'This is the new post'
]);

//Get/set/edit data
$document->title = 'The new title post';

//Save the document
$repo->saveDocument('first-post', $document);

//Get the document again
$document = $repo->getDocument('first-post');

//or delete it
$repo->deleteDocument('first-post');

处理目录

假设我们有以下结构的yaml文件

_ site
  |_ posts
    |_ first-post.yml
    |_ second-post.yml
  |_ articles
    |_ first-article.yml
    |_ second-article.yml
    |_ third-article.yml
use FlyCrud\Directory;
use FlyCrud\Document;
use FlyCrud\Formats\Yaml;

//Create a repository pointing to our site data using Yaml format:
$site = Directory::make(__DIR__.'/site', new Yaml());

//Get the posts directory
$posts = $site->getDirectory('posts');

//And the first post document
$post = $posts->getDocument('first-post');

//Or store a new document
$posts->saveDocument('third-post', new Document([
    'title' => 'My awesome third post',
    'intro' => 'This is the third post'
]));

数组访问和属性访问

为了简化对文档和目录的工作

  • 使用属性来访问目录(例如:$site->posts
  • 使用数组语法来访问文档(例如:$posts['first-post']

使用之前相同结构的示例

//Access to the first-article document
$article = $site->articles['first-article'];

//Save a new article
$site->articles['other-article'] = new Document([
    'title' => 'I like tomatoes'
    'intro' => 'Yes, they are red, rounded and tasty!'
]);

API

处理文档

文档是扩展ArrayObject的一些类

  • 实现了JsonSerializable接口,因此您可以轻松地将文档转换为json(json_encode($document)
  • 实现了魔法方法__get()__set()__isset()__unset(),因此您可以像操作属性一样操作值。
  • 数据被转换为stdClass对象,这允许您轻松地操作它。示例
use FlyCrud\Document;

//Create a document
$post = new Document([
    'title' => 'My post',
    'tags' => ['php', 'code'],
    'sections' => [
        [
            'title' => 'Section one',
            'body' => 'This is the first section of the document'
        ],[
            'title' => 'Section two',
            'body' => 'This is the second section of the document'
        ]
    ]
]);

//Use the properties to access to the data:
echo $post->title; // "My post"
echo $post->tags[0]; // "php"
echo $post->sections[0]->title; // "Section one"

//Modify the data
$post->section[1]->title = 'New title of the second section';