Skip to content

Instantly share code, notes, and snippets.

@phpwax
Forked from rossriley/Configuration.php
Created November 24, 2012 15:08
Show Gist options
  • Save phpwax/4140042 to your computer and use it in GitHub Desktop.
Save phpwax/4140042 to your computer and use it in GitHub Desktop.
Trait for defaults and settings
<?php
trait StaticDefaults{
protected static $_defaults = [];
public function __get($key){
if(is_callable($func = self::$_defaults[$key])) return $func();
return $func;
}
static public function defaults($defaults){
if(!is_array($defaults) && !$defaults instanceof ArrayAccess)
throw new \Exception("Supplied defaults could not be used. Array or Array Object required");
self::$_defaults += $defaults;
}
}
trait ArrayConstruct{
public function __construct($settings = []){
foreach($settings as $k => $v) $this->$k = $v;
}
}
abstract class Model{
use StaticDefaults, ArrayConstruct;
}
class ExampleModel extends Model {
}
class Application{
function __construct(){
$this->configure();
}
public function configure(){
Model::defaults(["db"=>["host"=>"127.0.0.1", "username"=>"user", "password"=>"pass"]]);
}
public function run(){
$model = new ExampleModel; //default db
print_r($model->db);
$model2 = new ExampleModel(["db"=>["host"=>"8.8.8.8", "username"=>"google", "password"=>"dns"]]); //overriden db
print_r($model2->db);
}
}
$app = new Application;
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment