millsoft
8/20/2017 - 10:48 AM

A simple Configuration Class for loading and saving to local config.json file.

A simple Configuration Class for loading and saving to local config.json file.

<?php

	/**
	 * Configuration
	 */

	class Conf{

			public static $configFile = "config.json";
		private static  $currentConfig = array();


		public static function get($key, $default = null){

			if(!isset(self::$currentConfig[$key])){
				return $default;
			}

			return self::$currentConfig[$key];
		}

		public static function set($key, $value){
			self::$currentConfig[$key] = $value;
			self::save();
		}

		/**
		 * Save current config from memory to config file
		 */
		private static function save(){
			$json = json_encode(static::$currentConfig);
			file_put_contents(static::$configFile, $json);
		}

		/**
		 * Load config file:
		 */
		private static function load(){
			if(!file_exists(static::$configFile)){
				//create a new config file:
				$emptyConf = json_encode(array());
				file_put_contents(static::$configFile, $emptyConf);
			}

			//read config file to array:
			$C = json_decode(file_get_contents(static::$configFile), true);
			static::$currentConfig = $C;
		}


	}