PHP MVC - Convert JSON to Model data

2019-02-25 19:42发布

So essentially I find myself writing a bunch of boiler plate code that takes info from a JSON encoded string and puts that data into the models used in my MVC web app. Is there an accepted method of doing this? Should every model have an associative array to model object converter? Should there be a utility class I write to do this? Basically, I am just trying to remove that code from my controllers to slim them down and I am new to PHP MVC. I am using Kohana 3.2 if that is of any relevance to the question.

EDIT:

I was asked to clarify. I receive data in string format that is JSON encoded (from a web service of my own writing - Java /w Jersey). So essentially, the models in my web app are not pulling their information from a database, but rather from a web service. Since the web service returns everything in JSON format, I find myself writing code that deals with that issue. The other way around, I can tell the GSON google code to convert JSON to a particular Java object. There does not seem to be a one liner way to do this in PHP. I am not talking about the stdClass object, but a model.

2条回答
放荡不羁爱自由
2楼-- · 2019-02-25 20:34

Kohana's models (ORM calss) only works with databse records. If you'd like to use Kohana you'll have to write new module based in ORM module. This module can have the actually do same things with model (load, save) but it's gona work with you input data.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-25 20:36

Your model must implement simple interface with method fromArray($array)

public function fromArray(array $array)
{
  foreach($array as $property => $value) {
     if(property_exists($this, $property) {
       $this->$property = $value;
     }
  }
}
查看更多
登录 后发表回答