PHP Datastorage Class (continued) - A Snack for the Road (
Page 4 of 4 )
Finally, if you are going to use cookies to store data, the constructor method should have the following code in it at the last If block.
else if($mode == "c")
{
if(isset($_COOKIE[$this-dataname]))
{
$this->items = unserialize($_COOKIE[$this->dataname]);
}
else
{
setcookie($this->dataname);
}
}
If the cookie is not yet set, then it is set, otherwise we retrieve the data from it just as we would with any of the other storage methods. This code simply sets a cookie by the default or the name specified. If you wish to supply additional parameters, such as expiration time, these optional arguments would need to be added to the constructor. You might also want to provide a backup plan in case the user has cookies disabled.
Wrapping it Up
Because all of this functionality is wrapped in a class, it can be included and extended by other classes easily.You can then let the err method do the work. You can also have multiple instances of the datastore in a document. Adding database connection capability through an abstraction class would give you a complete data storage solution, and the datastore could be used to provide preset connections and queries. If you come up with a good use make sure to share it.