Skip to content

Instantly share code, notes, and snippets.

@lastguest
Created September 7, 2018 12:52
Show Gist options
  • Save lastguest/b659906eaadbec0ce5d38c025ae86947 to your computer and use it in GitHub Desktop.
Save lastguest/b659906eaadbec0ce5d38c025ae86947 to your computer and use it in GitHub Desktop.
[PHP] CachedArray class
<?php
class CachedArray implements ArrayAccess {
private $cache,
$read,
$exists,
$update,
$delete;
public function __construct($callbacks){
if (is_callable($callbacks)){
$this->read = $callbacks;
} else {
$this->read = ($_=&$callbacks['get']) ?: false;;
$this->exists = ($_=&$callbacks['exists']) ?: false;
$this->update = ($_=&$callbacks['set']) ?: false;;
$this->delete = ($_=&$callbacks['unset']) ?: false;;
}
}
public function offsetGet($id){
return isset($this->cache[$id])
? $this->cache[$id]
: $this->cache[$id] = call_user_func($this->read, $id);
}
public function offsetSet($id, $value){
if ($this->update) call_user_func($this->update, $id, $value);
}
public function offsetUnset($id){
if ($this->delete) {
unset($this->cache[$id]);
call_user_func($this->delete, $id);
}
}
public function offsetExists($id){
return isset($this->cache[$id])
? true
: ($this->exists
? call_user_func($this->exists, $id)
: true
);
}
}
/*
$users = new CachedArray([
'get' => function($id){
return SQL::single("SELECT * FROM users WHERE id=?",[$id]);
},
'set' => function($id, $value){
$value = (array)$value;
if ($id) {
$value['id'] = $id;
SQL::insertOrUpdate("users",$value);
} else {
// Append
SQL::insert("users",$value);
}
return $value;
},
'unset' => function($id){
return SQL::exec("DELETE FROM users WHERE id=?",[$id]);
},
'exists' => function($id){
return !!SQL::value("SELECT 1 FROM users WHERE id=?",[$id]);
},
]);
// Fetch an User
$me = $users["root"];
// Create a new User
$users["mario.ross"] = [
'age' => 25,
'level' => 50,
'class' => 'paladine'
];
// Delete an User
unset($users["root"]);
// Check if an user exists
if (isset($users["lord.voldemort"])) ...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment