PHP code example of aalfiann / filebase

1. Go to this page and download the library: Download aalfiann/filebase library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aalfiann / filebase example snippets


// 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 = '[email protected]';
$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->query()->where('tags','IN','php')->results();

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


$db = new \Filebase\Database([
    'dir'            => 'path/to/database/dir',
    'backupLocation' => 'path/to/database/backup/dir',
    'format'         => \Filebase\Format\Json::class,
    'cache'          => true,
    'cache_expires'  => 60,
    'pretty'         => false,
    'safe_filename'  => true,
    'read_only'      => false,
    'validate' => [
        'name'   => [
            'valid.type' => 'string',
            'valid.

\Filebase\Format\Json::class

\Filebase\Format\Yaml::class

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

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


// 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'];


// 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();


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

$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);


$db = new \Filebase\Database([
    'dir' => '/path/to/database/dir',
    'validate' => [
        'name'   => [
            'valid.type' => 'string',
            'valid.ype'     => 'array',
            'valid.

// 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);
});

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

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

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

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



// Query LIKE Example: how about find all users that have a gmail account?
$usersWithGmail = $db->query()->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->query()
                    ->where('email','LIKE','@gmail.com')
                    ->orderBy('profile.name', 'ASC')
                    ->results();

// or just order the results by email address
$usersWithGmail = $db->query()
                    ->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->query()->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->query()->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->query()->select('name,age')->where('email','LIKE','@gmail.com')->results();

// Instead of returning users, how about just count how many users are found.
$totalUsers = $db->query()->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 == '[email protected]');
});


// 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();


// 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();