Introduction
JsonDb
is a PHP library designed to perform CRUD operations on a flat file. It can be deployed in situations where a traditional database may not be required. For example, a website guestbook or logging application errors. It also has query methods to return data based on search conditions. If you have the need to store data in a text file that needs to be queried, consider JsonDb
.
Before we get into the technical details on how JsonDb
works, let's first take a look at some code samples. JsonDb
uses namespaces and as a result, the class files need to be loaded. A simple call to the spl_autoload_register()
function can load the JsonDb
classes.
spl_autoload_register(function($class){
require $class .'.php';
});
Next, an instance of JsonDb
is required.
$db = new JsonDb();
$db = new JsonDb('path to save document');
The JsonDb
constructor takes an optional $documentStorePath
variable. This is the path to where data files will be saved. The default behavior is to save files in the directory of the currently executing script. Data files are saved with the .json extension. Remember if you save data files in your public
directory, these files will be accessible via the url.
For the first example, we begin with an introduction to the insert()
method. This method takes a standard object, then encodes it to a json format and saves it to file. The insert()
does not belong to the JsonDb
class. It is, in fact, a method of the JsonDocumentCollection
class. To get an instance of JsonDocumentCollection
, you must first invoke a dynamic property on the JsonDb
instance. To help explain this better, let's take a look at some examples.
$db->comments->insert(...);
$db->posts->insert(...);
$db->whatever->insert(...);
The properties comments, posts and whatever are dynamic properties of the $db
object. Dynamic property names are used as the data file names. For example, $db->comments
will return a new instance of JsonDocumentCollection
, which in turn will attempt to create a file named comments.json if it does not exist. The JsonDocumentCollection
instance will then expose all the methods needed to work with that file. The following examples demonstrate some of these methods.
Inserting an Object
$comment = new stdClass();
$comment->first_name = 'John';
$comment->last_name = 'Smith';
$comment->comment = 'This is my first comment';
$comment->date = date('Y-M-d H:i:s');
$db->comments->insert($comment);
The $comment
variable must be of type object
. Arrays are not supported. The insert()
method will assign a new property __object_id
to the $comment
object if it does not exist. This property contains a unique id that can later be used to update
, delete
or query
that comment.
Updating an Object
$objId = '14138983955446609b776c0';
$comment = new stdClass();
$comment->first_name = 'John';
$comment->last_name = 'Smith';
$comment->comment = 'Replace the current comment.';
$comment->date = date('Y-M-d H:i:s');
$db->comments->update($objId, $comment);
Using the __object_id
generated from an insert
, you can update an existing record using the update()
.
Removing an Object
$objId = '14138983955446609b776c0';
$db->comments->remove($objId);
Querying the Document Store
$jsonQuery = $db->comments->find(array('first_name' => 'John'));
$objId = '14138983955446609b776c0';
$jsonQuery = $db->comments->find($objId);
The find
method takes an array of search parameters. You can use multiple search parameters. Each search parameter performs an "AND
" operation on the query. The find()
method returns a new instance of JsonQuery
. If results have been found; call either fetchOne()
or fetch()
on the $jsonQuery
object. Calling the fetchOne()
method will return a single array from a search collection while the fetch()
method will return the entire search collection.
$comment = $jsonQuery->fetchOne();
$comments = $jsonQuery->fetch();
You can also limit the document collection result by using the limit()
method. The limit()
method takes two arguments ($start
, $count
). The limit()
method is useful should you need to present that data in a paging format.
$results = $jsonQuery->limit(2,3)->fetch();
Finally, the find()
method allows you to return documents based on search conditions. Multiple search conditions; result in an "AND
" operation. In some cases, the conditions may be more complex. Use the query()
method to specify a callback function, which can be used to customize the search results.
$results = $db->comments->query(function($document){
if($document->first_name == 'John' || $document->first_name == 'Suzan'){
return $document;
}
}, true);
"The Technical Details"
So now, a brief overview. When a document is inserted into the "document store", it opens the file in an append mode. At the time of calling insert()
, the object is json encoded and saved to disk and the file is then closed. In the case of an update
or remove
operation, both methods must load the entire data file to search for the object to update
or remove
. Once the object has been found, it is updated/removed from the loaded collection and the collection is saved to file with the new changes.
History
- 22nd October, 2014: Initial version