Skip to content

Instantly share code, notes, and snippets.

@r3wt
Created January 22, 2016 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save r3wt/2b82f3e63b3c0f2bf3c0 to your computer and use it in GitHub Desktop.
Save r3wt/2b82f3e63b3c0f2bf3c0 to your computer and use it in GitHub Desktop.
<?php
namespace UserFrosting\Util;
trait ArraySingleton
{
protected $data = [];
protected $defaults = [];
private static $instance = null;
protected function __construct(){}
public static function getInstance()
{
return (is_null(self::$instance) ? self::$instance = new self() : self::$instance);
}
public function setDefault($data)
{
$this->data = $this->defaults = $data;
}
public function fresh()
{
$this->data = $this->defaults;
}
public function get($key)
{
return (isset($this->data[$key]) ? $this->data[$key] : null);
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function __get($key)
{
return $this->get($key);
}
public function __set($key,$value)
{
return $this->set($key,$value);
}
public function all()
{
return $this->data;
}
public function has($key)
{
return array_key_exists($key, $this->data);
}
public function keys()
{
return array_keys($this->data);
}
public function __isset($key)
{
return $this->has($key);
}
public function remove($key)
{
unset($this->data[$key]);
}
public function __unset($key)
{
$this->remove($key);
}
public function clear()
{
$this->data = array();
}
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
$this->set($offset, $value);
}
public function offsetUnset($offset)
{
$this->remove($offset);
}
public function count()
{
return count($this->data);
}
public function getIterator()
{
return new \ArrayIterator($this->data);
}
}
<?php
namespace UserFrosting;
class Config implements \ArrayAccess, \Countable, \IteratorAggregate
{
use \UserFrosting\Util\ArraySingleton;
public static function create($config)
{
$self = static::getInstance();
$self->setDefault($config);
return $self;
}
}
<?php
// assuming you used an autoloader for UserFrosting and have already called registered autoloader.
// load the config. makes no difference how you store it.
$config = require 'config.php';
// the goal of this project is to make accessing config from any part of the app easy.
//create the config. local changes are never persisted.
$cfg = \UserFrosting\Config::create($config);
//pretend this is a function in some unrelated class, where passing $cfg/$config would be a real pain in the ass.
function fooBar()
{
$cfg = \UserFrosting\Config::getInstance();//tada now i have the config, and can access it like an array. now my code is much simpler because i used my brain. such wow
$foo = new \Foo($cfg['foo']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment