Skip to content

Instantly share code, notes, and snippets.

@cambiata
Created October 15, 2011 08:07
Show Gist options
  • Save cambiata/1289251 to your computer and use it in GitHub Desktop.
Save cambiata/1289251 to your computer and use it in GitHub Desktop.
Simplistic Kohana3 View_Model attempt
<?php
/**
*
* Simplistic View_Model attempt for Kohana 3
* @author Cambiata
*/
class View_Model {
public function render($viewfile=FALSE)
{
$viewfile = $viewfile ?: $this->get_viewfile();
$modeldata = $this->render_modeldata();
return View::factory($viewfile, $modeldata)->render();
}
public function __toString()
{
return $this->render();
}
//------------------------------------------------------------
private function get_viewfile()
{
$segments = explode('_', strtolower(get_class($this)));
if (count($segments) > 1) array_shift($segments);
return implode('/', $segments);
}
private function render_modeldata()
{
$modeldata = array();
$reflection = new ReflectionClass(get_class($this));
$public_properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($public_properties as $property)
{
$datakey = $property->name;
$modeldata[$datakey] = $this->$datakey;
}
$protected_properties = $reflection->getProperties(ReflectionProperty::IS_PROTECTED);
foreach ($protected_properties as $property)
{
$datakey = $property->name;
$modeldata[$datakey] = $this->$datakey;
}
$protected_methods = $reflection->getMethods(ReflectionProperty::IS_PROTECTED);
foreach ($protected_methods as $protected_method)
{
$datakey = $protected_method->name;
$modeldata[$datakey] = $this->$datakey();
}
// dump all data to $modeldata parameter - for easy debugging
$modeldata['modeldata'] = $modeldata;
return $modeldata;
}
}
@lukemorton
Copy link

Hmmm, just feels "hacky" to me. Kostache simply provides Kostache::set() for setting data. Surely that isn't too bad, I mean you already have ViewModel::render() which is public. Sure you could go down the magic route of PHPDoc style stuff, but again it feels like too much magic.

In ViewModel::render_modeldata() you could easily just skip a few predefined methods, and this way you could provide classes that extend ViewModel a way to exclude methods too!

In other news I will be releasing a cleaner, less convoluted update to Beautiful View that I would love you to take a look at if you have some spare time.

@cambiata
Copy link
Author

Thank you for your input! As I said, the purpose of creating this was fun and learning! :-)
I had an array with some methodnames to exclude, but took it away - wanted to keep it as minimalistic as possible.
I'm looking forward to the Beautiful view update! I'll check it out!

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