Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Created January 29, 2014 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/8698935 to your computer and use it in GitHub Desktop.
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...
<?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; // => &quot;Hello World&quot;!
@mindplay-dk
Copy link
Author

Nope - bad idea :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment