Variablen in Config.php ändern?

Hmm, hab hier mal was hingeschmiert... Funktioniert, könnte man aber sich noch verbessern.

PHP:
<?php
class TextConfig extends ArrayObject
{
	private $config = array();
	private $file;
	
	public function __construct()
	{

	}

	public function loadConfig($file)
	{
		$this->file = $file;
		$config = include($file);
		$this->config = unserialize($config);
	}
	
	public function saveConfig($file = null)
	{
		if(!$file)
			$file = $this->file;
		$config = "<?php\n return '";
		$config .= serialize($this->config);
		$config .= "'; \n?>";
		file_put_contents($file, $config);
	}
	
	public function offsetSet($index, $newval)
	{
		$this->config[$index] = $newval;
	}
	
	public function offsetGet($index)
	{
		return $this->config[$index];
	}
	
	public function debugMe()
	{
		print_r($this->config);
	}
}

?>
 
Guten Abend!
So bin wieder am heimischen PC! Also ich habe mich lange mit diesem Thema beschäftigt und habe mir ehrlich gesagt sehr lange die Zähne an einer Lösung mit parse_ini_file() ausgebissen. Dann bin ich auf die Methode mit dem Array in einer Datei gestoßen. Das stellte sich anfangs sehr leicht da. Endlich eine Klasse, die man einfach so runtertippen kann, doch dann kam ich ans speichern. Eine Lösung dafür hatte ich zwar, allerdings muss ich gestehen, dass diese nicht wirklich akzeptabel war. Dank Felix Jakobi konnte ich das Speichern und Einlesen nun stark optimieren. Kannte die Funktionen unserialize() und serialize() leider nicht. Eigentlich hatte ich noch eine Fehlermeldung in die __set()-Methode eingebaut, doch habe ich die rausgenommen, da es mir so möglich wird auch neue Einträge in die Konfigurations-Datei vorzunehemen, da zum Beispiel ein neues Modul installiert wurde. Habe mal einen Beispielaufruf unten an die Datei gehängt.
MfG, Andy

PHP:
<?php
error_reporting(E_ALL);

/***
* Class Config
* 
* The Config class allows reading the configuration-file.
* Furthermore you are able to edit, query and to save
* the new configuration.
* 
* @package Config
* @version 1.0
* @author Andreas Wilhelm <andreas.wilhelm@avedo.net>
* @copyright Andreas Wilhelm 
**/  
class Config
{
    private $file;
	private $config = array();

	/**
	* Cunstructor - Loads configuration from path
	*
	* @access public
	* @param Str $file
	* @return boolean
	*/
	public function __construct($file) 
	{
		// set path to config-file
		$this->file = $file;
		
		// save configuration to an array
		$config = include($file);
        $this->config = unserialize($config);
	}

	/**
	* __get() - Gets the value of an config-item
	*
	* @access: public
	* @param Str $key
	* @return String
	*/
	public function __get($key) 
	{ 
		if( !isset($this->config[$key]) )
		{
			throw new Exception('Cannot get item '.$key.'.');
		}
		
		return $this->config[$key]; 
	}
	
	/**
	* __set() - Assigns a new value to an entry of the config
	*
	* @access: public
	* @param Str $key
	* @param Str $value
	* @return NONE
	*/
	public function __set($key, $value) 
	{		
		$this->config[$key] = $value; 
	}
    
	/**
	* getConfig() - Returns the whole configuration as array
	*
	* @access: public
	* @return Array
	*/
	public function getConfig()
	{
		return $this->config;
	}
	
	/**
	* save() - Save configuration to file
	*
	* @access: public
	* @return Boolean
	*/
	public function save()
	{
        $config = "<?php\n return '";
        $config .= serialize($this->config);
        $config .= "'; \n?>";
        file_put_contents($this->file, $config);
	}
}

try
{
	$config = new Config('config.php');
	
    $title = $config->title;
    $copyright = $config->copyright;

    $config->error404 = 'Error 404 - Page could not be found.';
    $config->error500 = 'Error 500 - Internal Server Error.';

    $config->save(); 
}

catch(Exception $e)
{
    echo "Error:<br />";
    echo "<b>" . $e->getLine() . "</b>" . ": " . $e->getMessage() . "<br />";
}
?>
 
Hallo zusammen!
Mich hat etwas an der ersten Config-Klasse gestört. Man konnte nicht wirklich in der Konfigurations-Datei selbst erstmal Handanlegen und zudem gab es keine Kategorisierung der Daten. Daher habe ich eine neue Klasse geschrieben. Leider muss ich sagen, dass ich diese nicht wirklich ausreichend getestet habe, da ich momentan leider unter akuter Müdigkeit leide (man beachte die Uhrzeit). Trotzdem würde ich mir wünschen, dass vielleicht der eine oder ander mal einen Blick auf die Klasse wirft und verbesserungsvorschläge (speziel zur methode save()) macht. Freu mich natürlich auch über jeden tester.
MfG, Andy

PHP:
<pre>
<?php
error_reporting(E_ALL);

/***
* Class Configuration
* 
* The Configuration class allows reading a configuration-file.
* Furthermore you are able to add new entries to the configuration.
* Sure it is also possible to add, remove, edit, query and to save
* the new configuration. Finally it is important to 
* mention that this class supports the structuring of the 
* configuration in different sections, which sure can also
* be handled. Warning! This class can just handle existing 
* configuration files.
* 
* @package Configuration
* @version 0.5
* @author Andreas Wilhelm <Andreas2209@web.de>
* @copyright Andreas Wilhelm 
**/  
class Configuration
{
	// private class-variables
	private $config = array();
	private $file; 

	/**
	* Constructor - Loads configuration from path
	*
	* @access public
	* @param Str $file
	* @return NONE
	*/
	public function __construct($file) 
	{
		if(file_exists($file))
		{
			// set path to config-file
			$this->file = $file;
		
			// save configuration to an array
			$this->config = parse_ini_file($file, true); 
		}
		
		else
		{
			throw new Exception("{$file} cannot be found.");
		}
	}
    
	/**
	* addItem() - Adds a new item
	*
	* @access: public
	* @param Str $section
	* @param Str $key
	* @param Str $value
	* @return Boolean
	*/
	public function addItem($section, $key, $value)
	{
		if( !isset($this->config[$section][$key]) )
		{
			$this->config[$section][$key] = $value;
		
			return true;	
		}
		
		else
		{
			throw new Exception("Item {$section} - {$key} already exists.");
		}
	}
    
	/**
	* delItem() - Removes an item
	*
	* @access: public
	* @param Str $section
	* @param Str $key
	* @return Boolean
	*/
	public function delItem($section, $key)
	{
		if( isset($this->config[$section][$key]) )
		{
			unset($this->config[$section][$key]);
		
			return true;
		}
		
		else
		{
			throw new Exception("Cannot remove {$section} - {$key}.");		
		}
	}
	
	/**
	* setItem() - Assigns a new value to an entry of the config
	*
	* @access: public
	* @param Str $section
	* @param Str $key
	* @param Str $value
	* @return NONE
	*/
	public function setItem($section, $key, $value) 
	{		
		$this->config[$section][$key] = $value; 
	}

	/**
	* getItem() - Gets the value of an config-item
	*
	* @access: public
	* @param Str $section
	* @param Str $key
	* @return String
	*/
	public function getItem($section, $key) 
	{ 
		if( !isset($this->config[$section][$key]) )
		{
			throw new Exception("Cannot get item {$section} - {$key}.");
		}
		
		return $this->config[$section][$key]; 
	}
    
	/**
	* rnItem() - Renames an item
	*
	* @access: public
	* @param Str $section
	* @param Str $from
	* @param Str $to
	* @return Boolean
	*/
	public function rnItem($section, $from, $to)
	{
		if( isset($this->config[$section][$from]) && !isset($this->config[$section][$to]))
		{
			// move data to new section
			$this->config[$section][$to] = $this->config[$section][$from];
			
			// remove old section
			$this->delItem($section, $from);
			
			return true;
		}
		
		else
		{
			throw new Exception("Cannot rename item {$section} - {$from}.");
		}
	}
    
	/**
	* addSection() - Adds a section
	*
	* @access: public
	* @param Str $name
	* @return Boolean
	*/
	public function addSection($name)
	{
		if( !isset($this->config[$name]) )
		{
			$this->config[$name] = array();
		
			return true;	
		}
		
		else
		{
			throw new Exception("Section {$name} already exists.");
		}
	}
    
	/**
	* delSection() - Deletes a section
	*
	* @access: public
	* @param Str $name
	* @param Boo $ifEmpty
	* @return Boolean
	*/
	public function delSection($name, $ifEmpty = true)
	{
		if( isset($this->config[$name]) )
		{
			if( ($ifEmpty == true) && (count($this->config[$name]) > 0) )
			{
				throw new Exception("Section {$name} is not empty.");
			}
			
			else
			{
				unset($this->config[$name]);
		
				return true;	
			}	
		}
		
		else
		{
			throw new Exception("Cannot found section {$name}.");
		}
	}
    
	/**
	* getSection() - Returns all items of a section
	*
	* @access: public
	* @param Str $name
	* @return Array
	*/
	public function getSection($name)
	{
		$items = array();
		
		foreach( $this->config[$name] as $key => $value )
		{
			$items[$key] = $value;
		}
		
		return $items;
	}
    
	/**
	* getSections() - Returns all sections
	*
	* @access: public
	* @return Array
	*/
	public function getSections()
	{
		$sections = array();
		
		foreach( $this->config as $key => $value )
		{	
			if( is_array($value) )
			{
				$sections[] = $key;
			}
		}
		
		return $sections;
	}
    
	/**
	* rnSection() - Renames a section
	*
	* @access: public
	* @param Str $from
	* @param Str $to
	* @return Boolean
	*/
	public function rnSection($from, $to)
	{
		if( isset($this->config[$from]) && !isset($this->config[$to]))
		{
			// move data to new section
			$this->config[$to] = $this->config[$from];
			
			// remove old section
			$this->delSection($from, false);
			
			return true;
		}
		
		else
		{
			throw new Exception("Cannot rename section {$from}.");
		}
	}
    
	/**
	* getConfig() - Returns the whole configuration in an array
	*
	* @access: public
	* @return Array
	*/
	public function getConfig()
	{
		return $this->config;
	}
	
	/**
	* save() - Save Configuration to file
	*
	* @access: public
	* @return Boolean
	*/
	public function save()
	{
		$config = "";
	
		foreach( $this->config as $key => $value)
		{
			if( is_array($value) )
			{
				// save section name
				$config .= "[$key]\n";
				
				// save section items
				foreach( $value as $k => $v)
				{
					$config .= "$k = \"$v\"\n";
				}
			}
			
			else
			{
				// save item
				$config .= "$key = \"$value\"\n";
			}
		}
		
		echo $config;
        
        if( !@file_put_contents($this->file, $config) )
        {
			throw new Exception('Cannot save configuration.');
        }
	}
}

try
{
	$config = new Configuration('config.ini');
	
	// return whole configuration
	echo'<b>Configuration - getConfig():</b><br />';
	print_r( $config->getConfig() );
	
	// print out all all sections
	echo'<br /><b>Sections - getSections():</b><br />';
	print_r( $config->getSections() );
	
	// get all metatags
	echo'<br /><b>Metatags - getSection():</b><br />';
	print_r( $config->getSection('metatags') );
	
	// add a new section
	echo'<br /><b>-> Add section family | addSection()</b><br />';
	$config->addSection('family');
	
	// add a new item to metatags
	echo'<b>-> Add item likoer | addItem()</b><br />';
	$config->addItem('metatags', 'likoer', 'hannes');
	
	// add a new item to mom
	echo'<b>-> Add item mom | addItem()</b><br />';
	$config->addItem('family', 'mom', 'Jutta Wilhelm');
	
	// add a new item to mom
	echo'<b>-> Add item dad | addItem()</b><br /><br />';
	$config->addItem('family', 'dad', 'Wolfgang Wilhelm') ;
	
	// return whole configuration
	echo'<b>Configuration - getConfig():</b><br />';
	print_r( $config->getConfig() );
	
	// delete item
	echo'<br /><b>-> Delete Item Jutta | delItem()</b><br />';
	$config->delItem('family', 'mom');	
	
	// rename section mom
	echo'<b>-> Rename section family | rnSection()</b><br />';
	$config->rnSection('family', 'chaosfamily');
	
	// delete section
	echo'<b>-> Remove section chaosfamily | delSection()</b><br />';
	$config->delSection('chaosfamily', false);
	
	// rename item likoer
	echo'<b>-> Rename item likoer | rnItem()</b><br />';
	$config->rnItem('metatags', 'likoer', 'licensor');
	
	// edit item licensor
	echo'<b>-> Edit item licensor | setItem()</b><br />';
	$config->setItem('metatags', 'licensor', 'Andreas Wilhelm alias "avedo"');
	
	// return whole configuration
	echo '<br /><b>Configuration - getConfig():</b><br />';
	print_r( $config->getConfig() );
	
	// save to configuration file
	echo '<br /><b>Save configuration - save():</b><br />';
	$config->save();
	
	echo '<input type="text" name"licensor" value="' . $config->getItem('metatags', 'licensor') . '" />';
}

catch(Exception $e)
{
	echo'<b>Error:</b><br />';
	echo '<b>'.$e->getLine().': </b>'.$e->getMessage().'<br />';
}
?>
</pre>
 
Zuletzt bearbeitet von einem Moderator:
Zurück