Possible Duplicate:
PHP MVC – Convert JSON to Model data
Is there an easy way using vanilla PHP, a PHP library, or Kohana to easily marshall information from a json encoded object into a Kohana MVC model object? The json_encoded object has the same fields as the model object, but none of the functionality. Is there a generally accepted way of avoiding this silly dance?
It just feels like I am constantly writing code to move data around with code like:
$array = json_decode(returnsObject());
$model = Model::factory("model");
$model->field1 = $array['field1'];
$model->field2 = $array['field2'];
.....
Now obviously I have this in a method, but it seems outlandish that there is not a better method of doing this.
This is the easy way.
Controller in MVC design pattern is responsible only for extracting data from users request and passing it to model layer and current view. Your code example is actually a almost acceptable implementation of controller’s action … that’s of course, if you ignore the factory method anti-pattern and referring to domain objects as “models”.
You could extent the
Requestclass and add the method that extracts data from JSON string before returning it, but it would violate single responsibility principle.