diff --git a/flight/View.php b/flight/View.php index b10be08..e4dd04d 100644 --- a/flight/View.php +++ b/flight/View.php @@ -9,11 +9,59 @@ class View { public $path; public $template; + public $data = array(); + /** + * Constructor. + * + * @param string $path Path to templates directory + */ public function __construct($path = null) { $this->path = $path ?: (Flight::get('flight.views.path') ?: './views'); } + /** + * Gets a template variable. + * + * @param string $key Key + * @return mixed + */ + public function get($key) { + return $this->data[$key]; + } + + /** + * Sets a template variable. + * + * @param mixed $key Key + * @param string $value Value + */ + public function set($key, $value = null) { + // If key is an array, save each key value pair + if (is_array($key) || is_object($key)) { + foreach ($key as $k => $v) { + $this->data[$k] = $v; + } + } + else if (is_string($key)) { + $this->data[$key] = $value; + } + } + + /** + * Unsets a template variable. If no key is passed in, clear all variables. + * + * @param string $key Key + */ + public function clear($key = null) { + if (is_null($key)) { + $this->data = array(); + } + else { + unset($this->data[$key]); + } + } + /** * Renders a template. * @@ -23,7 +71,11 @@ class View { public function render($file, $data = null) { $this->template = (substr($file, -4) == '.php') ? $file : $file.'.php'; - extract($data); + if (is_array($data)) { + $this->data = array_merge($this->data, $data); + } + + extract($this->data); include $this->path.'/'.$this->template; }