An Introspective Builder Pattern Implementation

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:

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.

Now instead of our old solution, we can just instantiate the object and call its fromArray method.

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

Leave a comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>