From 1c7296042dba3b959cb1d8ff648bb823609043d9 Mon Sep 17 00:00:00 2001 From: oliver Date: Fri, 22 May 2015 14:21:53 +0200 Subject: [PATCH] implement loading models for Controller Components --- core/Component.inc | 75 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/core/Component.inc b/core/Component.inc index ae219970..a59c7464 100644 --- a/core/Component.inc +++ b/core/Component.inc @@ -80,6 +80,81 @@ return \nre\configs\AppConfig::$app['namespace']."controllers\\components\\$className"; } + + + + /** + * Construct a new (Controller) Component. + * + * @throws \nre\exceptions\DriverNotFoundException + * @throws \nre\exceptions\DriverNotValidException + * @throws \nre\exceptions\ModelNotValidException + * @throws \nre\exceptions\ModelNotFoundException + */ + protected function __construct() + { + // Load Models + $this->loadModels(); + } + + + + /** + * Load the Models of this Controller. + * + * @throws \nre\exceptions\DriverNotFoundException + * @throws \nre\exceptions\DriverNotValidException + * @throws \nre\exceptions\ModelNotValidException + * @throws \nre\exceptions\ModelNotFoundException + */ + protected function loadModels() + { + // Determine Models + $explicit = false; + $models = \nre\core\ClassLoader::stripClassType(\nre\core\ClassLoader::stripNamespace(get_class($this))); + if(property_exists($this, 'models')) + { + $models = $this->models; + $explicit = true; + } + if(!is_array($models)) { + $models = array($models); + } + // Models of parent classes + $parent = $this; + while($parent = get_parent_class($parent)) + { + $properties = get_class_vars($parent); + if(array_key_exists('models', $properties)) { + $models = array_merge($models, $properties['models']); + } + } + $models = array_unique($models); + + // Load Models + foreach($models as &$model) + { + try { + // Load class + Model::load($model); + + // Construct Model + $modelName = ucfirst(strtolower($model)); + $this->$modelName = Model::factory($model); + } + catch(\nre\exceptions\ModelNotValidException $e) { + if($explicit) { + throw $e; + } + } + catch(\nre\exceptions\ModelNotFoundException $e) { + if($explicit) { + throw $e; + } + } + } + } + } ?>