Skip to content

Instantly share code, notes, and snippets.

@geilt
Last active June 30, 2017 18:23
Show Gist options
  • Save geilt/0783a7b20f4d6b828f59d89192ed4e0f to your computer and use it in GitHub Desktop.
Save geilt/0783a7b20f4d6b828f59d89192ed4e0f to your computer and use it in GitHub Desktop.
Get Dot Notation Values with Caching.
<?php
/**
* This class assumes it is in some kind of framework.
* It has 'data' passed in, then the $this->var function will get data either in the $this->data object if $name is string
* or it will return from an object passed in.
* It converts the object into an array and keeps a copy in cache for later use so the json_encode and json_decode is not called
* multiple times.
*/
class View {
public __construct($data = null){
$this->cache = [];
$this->data = $data
}
public function var($name, $var = '', $default = '', $defaultOnEmpty = false){
if(is_string($name)) {
if(empty($this->{$name})) return $default;
$object = $this->{$name};
$hash = spl_object_hash($this->{$name});
} else {
if(empty($name)) return $default;
$object = $name;
$hash = spl_object_hash($name);
}
if(empty($var)) return $object;
if(!isset($this->cache[$hash])) $this->cache[$hash] = json_decode(json_encode($object), true);
$object = $this->cache[$hash];
$token = strtok($var, '.');
while ($token !== false) {
if (!isset($object[$token])) return $default;
$object = $object[$token];
$token = strtok('.');
}
if($defaultOnEmpty && empty($object)) return $default;
return $object;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment