Created
January 29, 2014 22:52
-
-
Save mindplay-dk/8698935 to your computer and use it in GitHub Desktop.
Sort of like the presenter pattern, I guess - but the View can proxy any view-model type (no base class required) and can e.g. html-encode or filter and of it's properties... plus you get auto-completion and inspections via the type-hint on $view in an IDE...
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 | |
/** | |
* This class acts as a proxy for arbitrary view-models | |
*/ | |
class View | |
{ | |
/** | |
* @var ViewModel raw view-model | |
*/ | |
public $raw; | |
public function __construct(ViewModel $model) | |
{ | |
$this->raw = $model; | |
} | |
protected function _filter($name, $value) | |
{ | |
// TODO real filters, duh | |
return htmlspecialchars($value); | |
} | |
public function __get($name) | |
{ | |
return $this->_filter($name, $this->raw->$name); | |
} | |
public function __set($name, $value) | |
{ | |
$this->raw->$name = $value; | |
} | |
public function __call($name, $params) | |
{ | |
$value = call_user_func_array(array($this->raw, $name), $params); | |
return $this->_filter($name, $value); | |
} | |
// TODO proxy ArrayAccess | |
} | |
/** the ViewModel can be anything */ | |
class ViewModel | |
{ | |
public $title; | |
public $text; | |
} | |
$model = new ViewModel(); | |
$model->title = 'Rasmus'; | |
$model->text = '"Hello World"!'; | |
/** @var View|ViewModel proxied view-model */ | |
$view = new View($model); | |
echo $view->text; // => "Hello World"! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nope - bad idea :-)