SQLiteDBArray: Using PHP interfaces.
I have been itching to write this one for a long time.
The idea behind this post is to go through PHP interfaces and see some of the cool things we can do with it. I just wrote something in a few hours so that I can use it as an example.
Checkout https://github.com/maheshgattani/SQLiteDBArray.
Its a simple, in memory, indexed array implementation in PHP using SQLite DB. I may be updating it later to enable associative arrays, more complex data types, file saves, serialization and other addons. What the first cut show is how easy it is to make your own data structure act like an array and the convenience you get by doing so.
I recommend reading about ArrayAccess Interface, Iterator Interface and Countable Interface. These interfaces when implemented, allow your object to act like an array. What I mean by 'act like' is, you will have access to elements its using [] operator. You can use for and foreach on your object and you can call count on the object to find out the number of items it is storing.
The use case: Write a wrapper on SQLite DB allowing array like access.
Benefits: It becomes plug and play alternative for arrays. It can act like a cache which is capable of SQL like queries. It can do all the complex logic SQL queries can, seamlessly. All this in the same class.
Drawbacks: You need to know how you are going to use this array. It is not as dynamic as a PHP array. For example you have to specify the name and type elements you elements you expect upfront. You can only use basic types integer, float and string. No nested arrays. So its beneficial only if you know the use case.
How do we do it?  By extending SQLite3 and implementing ArrayAccess, Iterator and Countable Interfaces in PHP. Its simpler than it sounds. I invite you to take a look at the Github repo. About 150 lines of codes do it. What stands out for me? The ability to swap the array with the new class seamlessly. Plug and play.
Example usage:
$db = new SQLiteDBArray(array('name' => SQLiteDBArray::$TEXT, 'age' => SQLiteDBArray::$INTEGER, 'address' => SQLiteDBArray::$TEXT, 'salary' => SQLiteDBArray::$REAL)); // Example writes $test = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20); foreach($test as $t) { $db[$t] = array('name' => 'testName' . $t); } // Example of count var_dump(count($db)); // Example reads using for for($i = 0; $i <= 20; $i++) { var_dump($db[$i]); } // Example reads using foreach foreach($db as $key => $value) { var_dump($key); var_dump($value); } // Example unset var_dump($db[1]); unset($db[1]); var_dump($db[1]);











