PHP Datastorage Class (continued) - Utility Methods (
Page 2 of 4 )
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.
do{
$temp = rand(1111111,9999999);
}while($data->is_item($temp));
$data->add_new_item($data_array,$temp);
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.
function is_value($val,$mode=0)
{
if($mode == 0)
{
return array_search($val,$this->items);
}
}
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.
function get_count()
{
if($this->items)
{
return count($this->items);
}
else
{
return 0;
}
}
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.
function destroy($mode="blank")
{
if($mode == "blank")
{
$mode = $this->mode;
}
if($mode == "s")
{
unset($_SESSION[$this->dataname]);
}
else if($mode == "f")
{
unset($this->items);
$this->store("f");
}
else if($mode == "c")
{
setcookie($this->dataname);
}
$this->items = null;
}
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.