Skip to content

Instantly share code, notes, and snippets.

@phred
Created November 16, 2012 20:45
Show Gist options
  • Save phred/4090771 to your computer and use it in GitHub Desktop.
Save phred/4090771 to your computer and use it in GitHub Desktop.
Simple PHP class wrapper for reading configuration from ini files
<?php
class ConfigParser {
function __construct($ini_file) {
$this->data = parse_ini_file($ini_file, true);
if ($this->data === FALSE) {
throw new Exception("Error reading file {$ini_file}");
}
}
function sections() {
return array_keys($this->data);
}
/**
* Retrieve a setting from the config file. Use the format
* "section.name" to specify the variable to retrieve. For example, with
* the ini file:
* ---
* [development]
* database=devel_db
* ---
* $parser->get("development.database") returns "devel_db"
*/
function get($key) {
list($section, $setting) = explode(".", $key);
$has_section = isset($this->data[$section]);
$has_setting = $has_section && isset($this->data[$section][$setting]);
return ($has_section && $has_setting ? $this->data[$section][$setting] : FALSE);
}
}
<?php
require('./ConfigParser.php');
$parser = new ConfigParser("test.ini");
assert(in_array("development", $parser->sections()));
assert(in_array("production", $parser->sections()));
assert($parser->get("development.database") === "devel_db");
assert($parser->get("development.user") === "franklin");
assert($parser->get("frabjous.day") === FALSE);
assert($parser->get("production.database") === "prod_db");
assert($parser->get("production.user") === "marko");
assert($parser->get("production.danger") === "severe");
echo "ALL TESTS PASSED :-)\n";
[development]
database=devel_db
user=franklin
[production]
database=prod_db
user=marko
danger=severe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment