Last active
January 2, 2016 09:09
-
-
Save galvao/8280931 to your computer and use it in GitHub Desktop.
Another way to write the exchangeArray method of the Model Class in ZF2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Please read the comments below in this Gist carefully as this approach has very important caveats. | |
| namespace Application\Model; | |
| class Foo | |
| { | |
| public $id; | |
| public $bar; | |
| public $baz; | |
| public $quux; | |
| public function exchangeArray($data) | |
| { | |
| $attributes = array_keys(get_class_vars(__CLASS__)); | |
| foreach($attributes as $attribute) { | |
| if (isset($data[$attribute])) { | |
| $this->$attribute = (!empty($data[$attribute]) ? $data[$attribute] : null); | |
| } | |
| } | |
| } | |
| } |
Author
@harikt Actually I've been realizing that, as Marco pointed out to us on Twitter, this is actually not a very good idea, and this is not even because of Hydrators, but:
- If you have any other attributes in that class, they'll fall into that foreach. I've just went through that with the $inputFilter attribute. So, stubborn as I am, I've added an isset check to see if the attribute is in the data array and that, of course, solved the problem.
- There are two specific cases where this code will fail miserably: boolean columns with false (or zero) as their value and int columns with zero as their value. In those cases is_empty will return true and so the value will be transformed into null.
So, by having one line per column you can do specific tests for specific columns and that's exactly what I'll do: I'll reverse things, going back to one column per line and do a is_null test for boolean and zero values, which will solve the issue.
@galvao I got the first problem.
About the 2nd problem : Can't we go with is_set() ?
I was also checking out https://github.com/dhrrgn/abstract-data-layer
In that rather than keeping as property, the fields are kept in an array.
Author
@harikt Ah, of course, isset would work. Been a long day of work, missed that =)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh I was trying something like this.