Read and write configuration using Sitemagic CMS

There are two mechanisms especially useful when it comes to storing configuration. The first allows us to store configuration in XML files, while the other uses a built-in Data Source called SMAttributes.

Storing configuration in an XML file
The SMConfiguration class allows us to read and write XML based configuration files such as this:
example.xml.php
<?php exit(); ?>
<?xml version="1.0" encoding="ISO-8859-1"?>
<entries>
    <entry key="Username" value="Administrator" />
    <entry key="Password" value="MySecretPassword" />
</entries>
Configuration is stored as key value pairs. The base configuration file for Sitemagic CMS (config.xml.php in the root of the Sitemagic CMS installation) is based on this format, and is also accessible for reading and writing using the SMConfiguration class.
Notice the .xml.php suffix in the filename and the exit() statement on the first line of code. This results in the configuration file being protected from direct access in the browser. Using only the .xml suffix will cause the configuration file to be unprotected, hence not suitable for storing e.g. username and password.
The following code is an example of how to read the database login details and language from config.xml.php.
Read from config.xml.php
$cfg = new SMConfiguration("config.xml.php");
$dbInfo = $cfg->GetEntry("DatabaseConnection"); // returns e.g. localhost;db;user;pass
$language = $cfg->GetEntry("Language"); // returns e.g. en or da
The following example will add or update an e-mail address within an unprotected configuration file. If the configuration file does not exist, it will automatically be created. If the e-mail address is not specified it will be added, and if it already exists it will be updated.
Write to test.xml in extension folder
$extensionPath = SMExtensionManager::GetExtensionPath($this->context->GetExtensionName());
$cfg = new SMConfiguration($extensionPath . "/test.xml", true);
$cfg->SetEntry("Email", "test@domain.com");
$cfg->Commit();

Storing configuration in attributes collection
Sitemagic CMS features a simple attribute collection that allows us to store key value pairs in a global key value pair collection. This is done using the specialized SMAttributes class.
// Write or update existing entries
SMAttributes::SetAttribute("MyExtensionUsername", "Administrator");
SMAttributes::SetAttribute("MyExtensionPassword", "MySecretPassword");

// Read entries (returns null if not defined)
$user = SMAttributes::GetAttribute("MyExtensionUsername");
$pass = SMAttributes::GetAttribute("MyExtensionPassword");
Notice how configuration entries are prefixed with MyExtension which is the name of our extension. This is good practice when using a shared resource. Generic names such as Username or Password are more likely to be overridden by a poorly designed extension.