As I am creating apis at my current work where a client could post json data, at one point I got really tired of checking whether an array key exists so I could call the corresponding setter in the object I am building up:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php $fromJson = array( 'attr1' => 'value1' 'attr2' => array( 'value1' 'value2' ), 'attr3' => 'value2' . . . ); $someObj = new SomeClass(); if (isset($fromJson['attr1']) { $someObj->setAttr1($fromJson['attr1']); } if (isset($fromJson['attr2']) { $someObj->setAttr1($fromJson['attr2']); } // and so on |
Usually, when I am stuck in a situation like this where I want to write more elegant code, I usually turn to open source projects.
Luckily for me, I was studying the code of Zend Form and I saw a good example of how my problem could be solved. The key is to have a method that will take in an array, loop through the keys and set the corresponding class instance variables via its setter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php class SomeClass { private $_attributeOne; private $_attributeTwo; public function fromArray(array $attributes) { foreach($attributes as $attribute => $value) { $method = sprintf('set%s', ucfirst($attribute)); if (method_exists($this, $method) { $this->$method($value); } } } public function setAttributeOne($attributeOne) { $this->_attributeOne = $attributeOne; } // and so on } |
Now instead of our old solution, we can just instantiate the object and call its fromArray method.
|
1 2 3 4 5 6 |
<?php $someObj = new SomeClass(); $someObj->fromArray(array( 'attributeOne' => 1, 'attributeTwo' => 2 )); |
Of course this assumes that your setters follow the pattern set[A-Z]{1}\w* and that that the key in json being posted has a corresponding setter based on the rules just given.
1 Comment