<?php

class DynamicConfigStorage {

	var $storageFilePath;
	var $fastAccessArray;	

	public function __construct($storageFilePath){
	 	$this->setStorageFilePath($storageFilePath);
	}

	// public 
	public function setStorageFilePath($storageFilePath){
	 	$this->storageFilePath = $storageFilePath;
	 	$this->fastAccessArray = array();
	}
	
	// set value for particular variable
	public function setValue($variableName, $variableValue, $disableSave=false){
		$this->fastAccessArray = $this->getArray();
		$this->fastAccessArray[$variableName] = $variableValue;
		$this->setArray($this->fastAccessArray, $disableSave);
	}
	
	// get value for particular variable
	public function getValue($variableName){
	
		if(empty($this->fastAccessArray))
			$this->fastAccessArray = $this->getArray();
		
		if(isset($this->fastAccessArray[$variableName])) return $this->fastAccessArray[$variableName];
		else return null;
		
	}	
	
	public function save(){
		$this->setFileContent($this->fastAccessArray);
	}
	
	// protected
	private function getArray($forceRead=false){
	 	if (!empty($this->fastAccessArray) && $forceRead==false){
	 		reset($this->fastAccessArray);
	 		return $this->fastAccessArray;
	 	}
		$content = Util::readFile($this->storageFilePath);
		if($content===false || $content=="") $content = serialize(array());
		return unserialize($content);
		
	}
	private function setArray($arr, $disableSave=false){
		$content = serialize($arr);
		if(!$disableSave){
			Util::writeFile($this->storageFilePath, $content);
		}
	}
}