Pavel Ko?enský - 2016-10-18 12:46:51 -
In reply to message 1 from Pavel Ko?enský
Yes, now it's OK. But why not to write the method for storing the data. It's a good rule to use one common method for I/O operations. And the result as bonus is more readable and concise code (see the add, update and delete methods).
For example:
/**
* Adds a key to Config file ( will be overwritten )
*
* @param mixed $key The key
* @param mixed $value And the key value
* @return boolean
*/
public function add($key, $value = '')
{
$this->config[$key] = $value;
return $this->writeConfigFile();
}
/**
* Update a existing key
*
* @param mixed $key The key
* @param mixed $value And the key value
* @return boolean
*/
public function update($key, $value = '')
{
// Since we are updating the data, if the key doesnt exist, abort!
if (!isset($this->config[$key]))
return false;
// Update key value
$this->config[$key] = $value;
return $this->writeConfigFile();
}
/**
* Delete an existing key
*
* @param mixed $key The key
* @return boolean
*/
public function delete($key)
{
// Since we are removing the data, if the key doesn't exist, abort!
if (!isset($this->config[$key]))
return false;
// Remove the key from array
unset($this->config[$key]);
return $this->writeConfigFile();
}
/**
* Encode and store the config data into the file
*
* @throws Exception If failed to write
* @return boolean
*/
private function writeConfigFile()
{
// Write data to the file and offcourse put a LOCK
if (!file_put_contents($this->configFile, json_encode($this->config), LOCK_EX)) {
throw new Exception('Failed to write data to config file. Make sure the file is writable.');
}
return true;
}