Skip to content

Instantly share code, notes, and snippets.

@freekrai
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freekrai/c594b1996d9dc25331f8 to your computer and use it in GitHub Desktop.
Save freekrai/c594b1996d9dc25331f8 to your computer and use it in GitHub Desktop.
Mini-Laravel-Like config setup
<?php
/*
This is a simple, Laravel-like config sysytem, add files to a config/ folder in the following setup:
config.php:
<?php
return array(
'site_name' => 'My Website',
'site_strapline' => 'This is my first website'
);
?>
---------
*/
class Config{
private $settings;
private $environment;
private $configPath;
public function __construct( $configPath = './config', $environment = '' ){
$this->configPath = $configPath;
$this->environment = $environment;
}
public function get($key){
$key = explode('.',$key);
$file = $key[0];
$key = $key[1];
$items = $this->load($file);
if( isset($items[ $key ]) ){
return $items[ $key ] ;
}
}
private function load($file){
$items = array();
$filename = array();
$filename[] = $this->configPath;
if( $this->environment != '' ){
$filename[] = $this->environment;
}
$filename[] = $file.'.php';
$filename = implode('/',$filename);
if( file_exists( $filename ) ){
$items = $this->mergeEnvironment($items, $filename);
}else{
$filename = array();
$filename[] = $this->configPath;
$filename[] = $file.'.php';
$filename = implode('/',$filename);
if( file_exists( $filename ) ){
$items = $this->mergeEnvironment($items, $filename);
}
}
return $items;
}
protected function mergeEnvironment(array $items, $file){
return array_replace_recursive($items, $this->getRequire($file));
}
private function getRequire($file){
return require $file;
}
}
/*
Then you can call your config setup as follows:
*/
$configPath = './config';
$config = new Config( $configPath );
echo $config->get('config.site_name');
/*
which will return the "config/config.php" file and check the returned array for the "site_name" key.
---------
If you want to use environments such as testing and production, then you can specify the environment
when you call your class and store the config files in a folder for each environment in the config/ folder.
For example create a testing/ folder and create config.php
*/
$configPath = './config';
$config = new Config( $configPath ,'testing');
echo $config->get('config.site_name');
/*
will see if "config/testing/config.php" exists and if it does, will load that, otherwise, it will check
for "config/config.php" and include that file instead.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment