Created
October 15, 2011 08:07
-
-
Save cambiata/1289251 to your computer and use it in GitHub Desktop.
Simplistic Kohana3 View_Model attempt
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 | |
/** | |
* | |
* 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; | |
} | |
} |
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
Hmmm, just feels "hacky" to me. Kostache simply provides
Kostache::set()
for setting data. Surely that isn't too bad, I mean you already haveViewModel::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 extendViewModel
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.