Skip to content

Instantly share code, notes, and snippets.

@kijtra
Last active March 11, 2016 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kijtra/5d4db148ccc402deb0d7 to your computer and use it in GitHub Desktop.
Save kijtra/5d4db148ccc402deb0d7 to your computer and use it in GitHub Desktop.
#PHP Simple data container
<?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;
}
}
}
@kijtra
Copy link
Author

kijtra commented Mar 11, 2016

add parent() and name() and has() method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment