FaaPz/PDO

Mapping undefined json properties

Closed this issue · 2 comments

This is more a question about a good practice than a issue.

I've created a api using slim and pdo for crud operations from a angular frontend app.
Some tables are quite big with several nullable columuns.
This means that for most cases the posted json will not be complete with all column data.

exemple:

        $item= json_decode($req->getBody());
        $insertStatement = $pdo->insert(array('prop1', 'prop2', 'prop3',...))
                               ->into('table')
                               ->values(array($item->prop1, $item->prop2, $item->prop3,...) ));

when posting something like this...

{"prop" : "foo" , "prop2" : "bar"}

...php logs a error like this:

PHP Notice: Undefined property: stdClass::$prop3 in /home/... on line ...

As prop3 is not present in json.

It works, anyway...
However this is not a clean implementation, and for huge ammount of requests logs will grow very fast.
This can be avoided by using php isset(), but doing it for all properties code will become huge and messy.

What I want to ask is a suggestion for a clean way to perform this mappings.

Thank you so much,

Hey,

Like you said, you can use either isset, or the coalescing operator from php7.0.

But as you said, it's not really an issue with the library.

kwhat commented

This is totally off topic, but what I usually do is create \JsonSerializable objects to represent my API's view layer. Then use a library like https://github.com/cweiske/jsonmapper to map the json into the class. You can probably get away with decoding the json to an array and passing that array to the constructor to fill out the object. I usually create both __set() and __get() that throw exceptions to ensure you don't get out of sync.

class JsonView extends \JsonSerializable {
    public $prop1;
    public $prop2;
    public $prop3;

    public __construct(array $values) {
         foreach ($values as $key => $value) {
              $this->{$key} = $value;
         }
    }

    public function __get($key) {
        throw new \Exception("Invalid property");
    }

    public function __set($key, $value) {
        throw new \Exception("Invalid property");
    }

   final public function jsonSerialize() {
       return $this;
   }
}