Думаю сгодится, хотя ничего особенного.
Предоставляет доступ к конфигурационнуму файлу.
Конструктор принимает два аргумента:
string $path - Путь к файлу. Конфиг должен представлять из себя JSON файл.
int $access - Доступ: Read-Only (0), Возможность записать новые данные или изменить существующие как без сохранения (1), так и с сохранением (2).
Будьте внимательны при передаче аргументов и следите за их типами, если будет принят не тот тип, который ожидается, то будет выброшено исключение.
Незабудьте при вызове методов, выбрасывающих исключения, отлавливать эти самые исключения.
Либо через try {} catch {}, либо через set_exception_handler()
class Configuration {
/**
* @var array Storage for data
*/
private $data = array();
/**
* @var string Path to configuration file
*/
private $path;
/**
* @var int Access to config
*/
private $access;
/**
* Constructor
* @param string $path Path to configuration file
* @param int $access Access to config: 0 - read-only; 1 - Allow change items; 2 - Allow change items and save changes.
* @throws InvalidArgumentException
* @throws Exception
* @return Configuration
*/
public function __construct($path, $access = 0) {
if (!is_string($path)) {
throw new InvalidArgumentException('Argument path must be a string');
}
if (!is_int($access)) {
throw new InvalidArgumentException('Argument access must be a integer');
}
if ($access < 0 || $access > 2) {
throw new Exception(
'Access parameter must have one of the following values:'
. ' 0 - read-only; 1 - Allow change items; 2 - Allow change items and save changes.'
);
}
if (!is_file($path)) {
throw new Exception('Unable to load configuration. File "' . $path . '" is not exists.');
}
$data = json_decode(file_get_contents($path), true);
if (!is_array($data)) {
throw new Exception('Unable to load configuration. File "' . $path . '" has wrong format.');
}
$this->path = $path;
$this->data = $data;
$this->access = $access;
}
public function __destruct() {
if ($this->access === 2) {
file_put_contents($this->path, json_encode($this->data));
}
}
/**
* Get item
* @param string $name Name of item
* @return mixed
*/
public function __get($name) {
return array_key_exists($name, $this->data) ? $this->data[$name] : null;
}
/**
* Set item
* @param string $name Name of item
* @param mixed $value Value of item
* @throws Exception
* @return void
*/
public function __set($name, $value) {
if ($this->access == 1) {
$this->data[$name] = $value;
} else {
throw new Exception('Read-only storage. You must change type of access.');
}
}
/**
* Check item for exists
* @param string $name Name of item
* @return boolean
*/
public function __isset($name) {
return array_key_exists($name, $this->data);
}
/**
* Unset item
* @param string $name Name of item
*/
public function __unset($name) {
if (array_key_exists($name, $this->data)) {
unset($this->data[$name]);
}
}
}