Tuesday, April 2, 2019

php notes: a directory full of json

Like I said in 2015,
Good lord, I know I'm not impressing anyone by digging on PHP, but man does it do a good job making easy things easy.
For a while now, I've liked doing my serverside plumbing in PHP and keeping my UI options open in javascript.

One of my favorite robust poor-man-db's paradigms is storing flat JSON files in directory - roughly, a directory is like a table, and each file is row. (GUID-ish filenames acts as a rowid). There are some downsides (it's not easy to rearrange columns, reading in a whole table is a large-ish amount of file reads, etc) but it's super-robust, hyper-portable, easy to implement and simple to operate on the data without simple text editors.

And sometimes, I just like to squirt a whole dang "table" like this into a page - here's some PHP that I'm sure I've recreated many times that does that:
    function dirOfJsonToFilesToJsonString($dir) {
        $files = array_diff(scandir($dir), array('.', '..'));
        $guts = array();
        foreach ($files as $i => $file) {
            $raw = file_get_contents("$dir/$file");
            $guts[$file] = json_decode($raw, true);
        }
        return json_encode($guts);
    }
That comedy gem wraps the full table contents as a JSON object/map string, and then I can let javascript do all the UI work.

Again, no one is impressed, but I'm one of those who believes in taking PHP seriously ;-)

No comments:

Post a Comment