Last active
March 11, 2016 16:11
-
-
Save kijtra/5d4db148ccc402deb0d7 to your computer and use it in GitHub Desktop.
#PHP Simple data container
This file contains 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 | |
/* | |
// Usage | |
$container = new Container(); | |
// Basic use | |
$container->aa = 'a'; | |
// Its No error, and added hierarchical data. | |
$container->bb->cc->dd->ee = 'abcde'; | |
// Get data by array | |
$arr = $container->bb->cc->array(); | |
// Get parent object | |
$parent = $container->bb->cc->parent(); | |
// Get current property name | |
$name = $container->bb->cc->parent()->name();// string "bb" | |
*/ | |
class Container implements IteratorAggregate | |
{ | |
private static $storage; | |
private static $names = array(); | |
public function __construct($data = array()) | |
{ | |
if (null === self::$storage) { | |
self::$storage = new \SplObjectStorage(); | |
self::$storage->attach($this, null); | |
self::$names[self::$storage->getHash($this)] = '!root'; | |
} | |
if (!empty($data) && is_array($data)) { | |
foreach($data as $key => $val) { | |
if ($this->isValidName($key)) { | |
if (is_array($val)) { | |
$this->$key = $this->setObject($key, $val); | |
} else { | |
$this->$key = $val; | |
} | |
} | |
} | |
} | |
} | |
public function name() | |
{ | |
return self::$names[self::$storage->getHash($this)]; | |
} | |
public function array() | |
{ | |
return $this->toArray($this); | |
} | |
public function parent() | |
{ | |
return self::$storage->offsetGet($this); | |
} | |
public function has($name) | |
{ | |
return $this->__isset($name); | |
} | |
public function __get($name) | |
{ | |
return $this->$name = $this->setObject($name); | |
} | |
public function __isset($name) | |
{ | |
return property_exists($this, $name); | |
} | |
public function __toString() | |
{ | |
return ''; | |
} | |
public function getIterator() { | |
return new ArrayIterator($this); | |
} | |
private function setObject($name, $value = array()) | |
{ | |
$object = new self($value, $name, self::$storage); | |
self::$storage->attach($object, $this); | |
self::$names[self::$storage->getHash($object)] = $name; | |
return $object; | |
} | |
private function isValidName($value) | |
{ | |
return (is_string($value) && preg_match('/\A[_a-zA-Z][_a-zA-Z0-9]+\z/', $value)); | |
} | |
private function toArray($data) | |
{ | |
if ($data instanceof self) { | |
if (!empty($data)) { | |
$arr = array(); | |
foreach(get_object_vars($data) as $key => $val) { | |
$arr[$key] = $this->toArray($val); | |
} | |
if (!empty($arr)) { | |
return $arr; | |
} | |
} | |
} else { | |
return $data; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
add
parent()
andname()
andhas()
method.