Simple Environment Config (PHP Snippet)

Never ended up using it, was intended for tiny scripts that needed some simple environmental config.

_config.php

<?php
 
function _config($for=null)
{
 
    $path    = dirname(__FILE__) . '/config.xml';
    $sig     = md5($path);
 
    if (defined($sig))
    {
        $config = unserialize(constant($sig));
    }
        else
    {
        $config  = (object) array();
        $xml     = simplexml_load_file(dirname(__FILE__) . '/config.xml');
 
        foreach ($xml->environments->children() AS $env)
        {
            $environment              = $env->attributes()->name;
            $config->{$environment}   = (object) array();
 
            foreach ($env->children() AS $variable)
            {
                $config->{$environment}->{$variable->attributes()->name} = (string) $variable;
            }
        }
 
        define($sig,serialize($config));
    }
 
    if ($for==null)
    {
        $for = getenv('ENVIRONMENT');
 
        if (empty($for))
        {
            $for = 'dev';
        }
    }
 
    return isset($config->{$for}) ? $config->{$for} : (object) array();
 
}

config.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<config>
 
    <environments>
        <environment name="dev">
            <variable name="mysql_host">localhost</variable>
            <variable name="mysql_port">3306</variable>
            <variable name="mysql_user">root</variable>
            <variable name="mysql_password">root</variable>
            <variable name="mysql_database">portal</variable>
        </environment>
    </environments>
 
</config>

Leave a Reply