Skip to content

Instantly share code, notes, and snippets.

@kfriend
Last active December 25, 2015 10:59
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 kfriend/6965893 to your computer and use it in GitHub Desktop.
Save kfriend/6965893 to your computer and use it in GitHub Desktop.
PHP: Simple repository classes
<?php
// Todo
// - Add arrary-like iterating capabilities
class Repository
{
protected $attributes = array();
public function __construct(array $attributes = array())
{
$this->attributes = $attributes;
}
public function set($item, $value)
{
$this->attributes[$item] = $value;
}
public function place($path, $value)
{
array_set($this->attributes, $path, $value);
}
public function merge(array $items)
{
$this->attributes = array_merge($this->attributes, $items);
}
public function append($item, $data)
{
if ($this->missing($item))
{
$this->set($item, $data);
return;
}
if (is_array($this->attributes[$item]))
{
$this->merge(array($item => (array) $data));
return;
}
$this->attributes[$item] .= $data;
}
public function get($item, $default = null)
{
return (isset($this->attributes[$item])) ? $this->attributes[$item] : $default;
}
public function find($path, $default = null)
{
return array_get($this->attributes, $path, $default);
}
public function all()
{
return $this->attributes;
}
public function exists($item)
{
return isset($this->attributes[$item]);
}
public function has($item)
{
return $this->exists($item);
}
public function missing($item)
{
return !$this->exists($item);
}
public function isEmpty($item)
{
return empty($this->attributes[$item]);
}
public function notEmpty($item)
{
return !$this->isEmpty($item);
}
public function remove($item)
{
unset($this->attributes[$item]);
}
public function reset($item, $default = null)
{
$this->attributes[$item] = $default;
}
public function __get($attribute)
{
return $this->get($attribute);
}
public function __set($attribute, $value)
{
$this->set($attribute, $value);
}
}
<?php
class StaticRepository
{
protected static $repository;
public static function setRepository(Repository $repo)
{
static::$repository = $repo;
}
public static function getRepository()
{
return static::$repository;
}
public static function __callStatic($method, $args)
{
if (method_exists(static::$repository, $method))
{
return call_user_func_array(array(static::$repository, $method), $args);
}
throw new BadMethodCallException("{$method} method doesn't exists in " . get_called_class() . ' or its repository');
}
public function __get($attribute)
{
return static::$repository->{$attribute};
}
public function __set($attribute, $value)
{
static::$repository->{$attribute} = $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment