Created
November 6, 2014 12:50
-
-
Save nmenglund/98ace11a49f77ba8cee7 to your computer and use it in GitHub Desktop.
PersistentArray, an ArrayObject extension to maintain state in a JSON file (for running batch scripts etc.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| * Example: | |
| * | |
| * $store = PersistentArray::load('example.json'); | |
| * echo "Key is: " . (isset($store['key']) ? $store['key'] : 'not set') . "\n"; | |
| * $store['key'] = '123'; | |
| * | |
| * Running this twice will yield: | |
| * | |
| * Key is: not set | |
| * Key is: 123 | |
| * | |
| */ | |
| class PersistentArray extends ArrayObject | |
| { | |
| private $filename = null; | |
| public static function load ($filename) | |
| { | |
| if (file_exists($filename) && filesize($filename)) | |
| { | |
| $data = json_decode(file_get_contents($filename), true); | |
| } | |
| else | |
| { | |
| $data = array(); | |
| if (!touch($filename)) | |
| { | |
| die("Could not create $filename"); | |
| } | |
| } | |
| $created = new self($data); | |
| $created->filename = $filename; | |
| register_shutdown_function(array($created,'shutdown')); | |
| return $created; | |
| } | |
| public function shutdown () | |
| { | |
| file_put_contents($this->filename, json_encode($this->getArrayCopy(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment