3

I'm starting a new project that uses couchbase (a noSQL database that stores objects in json format), together with php.

The thing is that it would be really easy to work with them both if I could have something that maps json into one of my own php classes (and vice versa).

Do you know any library for that?

Ikke
  • 99,403
  • 23
  • 97
  • 120
ThisIsErico
  • 1,885
  • 2
  • 19
  • 24
  • 1
    Doesn't that standard couchdb client library for PHP does this out of the box? What have you tried so far? How do you do it right now? – hakre Dec 27 '12 at 21:54
  • In any case start with json_decode to turn your json object into a stdClass. – Damien Overeem Dec 27 '12 at 21:55
  • Well, couchbase provides a method (view("stuff", "stuff")) that already does the json_decode. So far I already have a php structure. The thing is that I need to map those json attributes in my own class attributes. Suppose the json has something like this in the middle: ... "foo": "aloha123", "bar": bye123"... In my class I have an attribute foo and another attribute bar. I need the mapper to put those values into my own class attributes. I could implement a mapper that does so (so far is what I have), but I would like to know if something more sofisticated already exists. – ThisIsErico Dec 27 '12 at 22:01
  • possible duplicate of [json\_decode to custom class](http://stackoverflow.com/questions/5397758/json-decode-to-custom-class) – cweiske Jan 22 '14 at 15:10

3 Answers3

2

One way to start is to look (or use) the "Basement" Library that is available here: https://github.com/Basement/Basement

This library uses json_decode/encode. Hope that will help you.

Tug Grall
  • 3,410
  • 1
  • 14
  • 16
2

You may use our JSONmapper to map from JSON to your PHP classes. It unfortunately does not support mapping back (yet).

cweiske
  • 30,033
  • 14
  • 133
  • 194
0

Tug already mentioned Basement, which will provide that functionality of "models" in the near future like you know it from ORM systems.

Aside from that, mapping your plain old php objects to JSON is very easy, thanks to the nature of json_encode/decode. Since you can pass it an arbitary object and it will store it as JSON, thats basically the only thing you need at hand. If you need more infos about JSON and PHP, my blog post is a good start: http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP

If you use Basement, it makes it a little bit easier for you since it allows you to transform PHP types into JSON behind the scenes automatically (or write your own mapper if needed).

If you have a specific example that you want to build, let me know and I'd be happy to provide an example!

daschl
  • 1,124
  • 6
  • 11