Skip to content

Instantly share code, notes, and snippets.

@peebeebee
Forked from cambiata/View_Model
Created August 10, 2012 18:10
Show Gist options
  • Save peebeebee/3316256 to your computer and use it in GitHub Desktop.
Save peebeebee/3316256 to your computer and use it in GitHub Desktop.
Simplistic Kohana3 View_Model attempt
<?php defined('SYSPATH') or die('No direct script access.');
/**
*
* Simplistic View_Model attempt for Kohana 3, Based on Cambiata's viewmodel
* @author peebeebee
*/
class View extends Kohana_View {
const prefix = 'var_';
public function before() { }
public function after() { }
public function __construct($file = NULL, array $data = NULL)
{
$this->before();
$this->set($this->get_modeldata());
if($file === NULL)
$file = $this->get_viewfile($file);
parent::__construct($file, $data);
}
private function get_viewfile($file)
{
$segments = explode('_', strtolower(get_class($this)));
if (count($segments) > 1) array_shift($segments);
return implode('/', $segments);
}
private function get_modeldata()
{
$data = array();
$reflection = new ReflectionClass(get_class($this));
$public_properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($public_properties as $property)
{
$key = $this->create_key($property->name);
if($key) $data[$key] = $this->{$property->name};
}
$public_methods = $reflection->getMethods(ReflectionProperty::IS_PUBLIC);
foreach ($public_methods as $public_method)
{
$key = $this->create_key($public_method->name);
if($key) $data[$key] = $this->{$public_method->name}();
}
return $data;
}
private function create_key($datakey)
{
$prefix = strlen(self::prefix);
$pos = stripos($datakey, self::prefix);
return ($pos !== FALSE) ? substr($datakey, $pos+$prefix) : FALSE;
}
public function render($file = NULL)
{
$rendered = parent::render($file);
$this->after();
return $rendered;
}
}
@peebeebee
Copy link
Author

Can't use the standard factory method for now. But that could be easily fixed.

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