PHP Classes

json_decode after reading the file?

Recommend this page to a friend!

      Flat Config  >  All threads  >  json_decode after reading the file?  >  (Un) Subscribe thread alerts  
Subject:json_decode after reading the file?
Summary:The config data decoding must be done.
Messages:3
Author:Pavel Ko?enský
Date:2016-10-17 15:05:41
 

  1. json_decode after reading the file?   Reply   Report abuse  
Picture of Pavel Ko?enský Pavel Ko?enský - 2016-10-17 15:05:41
I think the config data decoding is missing after file_get_contents. I don't know any automatic file decoding would have taken place while data reading with this function. The file_get_contents() function returns a string (or FALSE). Am I wrong?

  2. Re: json_decode after reading the file?   Reply   Report abuse  
Picture of Miraz Mac Miraz Mac - 2016-10-18 05:10:19 - In reply to message 1 from Pavel Ko?enský
Oops! Sorry, I accidentally removed that line. The class has been updated. Please check and see if there are any other issue(s).
Thanks and sorry for my bad English :p

  3. Re: json_decode after reading the file?   Reply   Report abuse  
Picture of Pavel Ko?enský 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;
}