HomePHP Page 2 - PHP Datastorage Class (continued)
Utility Methods - PHP
In the first part of this two-part article, you started to learn about using alternatives to databases for storing data; specifically, we started to work on creating a class that can handle flat files, session variables, and cookies. This second part picks up right where we left off last time.
There are several utility methods in this class that can make your life much easier when using the datastore. The first is is_item. This method allows you to determine if an item with the key you are looking for is there and returns false if it isn't. You can use is_item to ensure that each key is unique using the following code.
As long as is_item finds a key that matches your random number the loop will continue until it finds a unique one.
Another useful method is is_value. This method searches for the value you specify and will return true if it finds it, false if it doesn't. This method has a mode selector in its arguments as well, to allow future enhancements to the method.
A utility method that is likely to get used in every page that uses the datastore is get_count. This method simply returns the number of items in the items array. If you have no records stored you can determine this and provide the proper feedback to the user.
Once you're done with the data you have stored and need to initialize it, use the destroy method. This will unset your session variable, erase your flat file or eat your cookie depending on which storage mode you have selected.
One final utility method allows you to delete an item from the items array. delete_item will delete an item with the key that you specify with the first and only argument.
function remove_item($id) { if(isset($this->items[$id])) { unset($this->items[$id]); $this->edited = true; return true; } else { $this->err("Could not find and remove $id"); return false; } }
As with other parts of the datastore class, there are probably plenty of additional possibilities for modifications and other utility methods to reduce the amount of code you would need to write as part of your application.