Simple PHP Design

I’m nerding out over this. Simplicity, elegance, efficiency; these passions are those that make programmers. I had the opportunity today to design a simple, elegant mechanism that made me genuinely excited. Cast your eyes on the snippet below:

input([“name”=>”FilingStatus”,
“label”=>”Filing Status”,
“type”=>”select”,
“options”=> [
“default”=>”Single”,
“Married — Filing Jointly”,
“Married — Filing Separately”,
“Head of Household”
],
“row”=>”FilingStatus”],$r);

Let me guide you through the thought process here. I started with this lovely little function input() as a way to programatically generate input elements using PHP. I had a page full of them to write, so a wrapper function was a great time saver. It takes as argument an array populated with attributes. The template for its use looks like this:

input([“name”=>” ”,
“label”=>” ”,
“type”=>” ”,
“row”=>” ”],$r);

It will then generate a label, an input of type type, and pre-populate it with a respective value from the database this PHP page connects to.


Now, as I came down the list of input types to implement, I arrived at the select input type. Ah, one element with multiple sub-elements. Following the existing paradigm, that was easy enough to model by inserting a sub-array for the options. The select-specific template looked as follows (three dots indicating more than two options could be used):

input([“name”=>” ”,
“label”=>” ”,
“type”=>” ”,
“options”=> [
” ”,
“ ”,


],
“row”=>” ”],$r);


My most exciting moment came when it occurred to me that it was desirable to indicate to the function which option was to be the default. How would I do this? I could pass along another top-level parameter in the array (something like default=>” “)… ButI had a better way!

input([“name”=>” ”,
“label”=>” ”,
“type”=>”select”,
“options”=> [
“default”=>” ”,
“ ”,

],
“row”=>” ”],$r);

I was so excited. Now, using just a simple if(data[‘options’][default]==$option) check, I could decide whether or not to add the attribute to the option when echoing it.


Granted, this paradigm only works for an attribute that is uniquely identified. It does not readily expand to attributes that could possibly apply to multiple options at once. For the use case though, this is a simple, efficient way to add the default option functionality.

)