-
-
Save phpwax/4140042 to your computer and use it in GitHub Desktop.
Trait for defaults and settings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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