Skip to content

Instantly share code, notes, and snippets.

@kijtra
Last active March 19, 2016 15:05
Show Gist options
  • Save kijtra/8df303956708b0c2fbac to your computer and use it in GitHub Desktop.
Save kijtra/8df303956708b0c2fbac to your computer and use it in GitHub Desktop.
#PHP simple flexible data container with ArrayObject
<?php
function depot()
{
static $container = null;
if (null === $container) {
$container = new \ArrayObject(array(), $flag);
}
$flag = \ArrayObject::ARRAY_AS_PROPS;
$args = func_get_args();
$num = func_num_args();
if (2 === $num) {
$value = (is_array($args[1]) ? (object)$args[1] : $args[1]);
$keys = explode('.', $args[0]);
$last = count($keys) - 1;
$cur =& $container;
foreach($keys as $i => $key) {
if (empty($key)) {
continue;
}
if ($i !== $last) {
if (
($cur instanceof \ArrayObject && $cur->offsetExists($key)) ||
(is_array($cur) && array_key_exists($key, $cur))
) {
$cur =& $cur[$key];
} else {
$cur[$key] = new \ArrayObject(array(), $flag);
$cur =& $cur[$key];
}
} else {
if (is_array($value) || $value instanceof \stdClass) {
$cur[$key] = new \ArrayObject($value, $flag);
} else {
$cur[$key] = $value;
}
}
}
return $cur;
}
elseif (1 === $num) {
if (!$container->count()) {
return;
}
$keys = explode('.', $args[0]);
$cur = $container;
foreach($keys as $key) {
if (empty($key)) {
continue;
}
if (
($cur instanceof \ArrayObject && $cur->offsetExists($key)) ||
(is_array($cur) && array_key_exists($key, $cur))
) {
$cur = $cur[$key];
} else {
return null;
}
}
return $cur;
}
else {
if ($container->count()) {
return $container;
}
}
}
/*
// Set
depot('key', 'val');
// Get
$val = depot('key');
// Set nested
depot('foo.var', 'baz');
// dump
var_dump( depot('foo') );
// result
ArrayObject(
'var' => 'baz'
)
// Get all
$all = depot();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment