Reply to comment

Terse Javascript Alternations, and the Frameworks' Problem with SQL


Here's a snippet of javascript that breaks up a phone number into its parts, if it's formatted in the common formats.

    var cell = namesArray[rownum]['Cell'];
    (cell_parts = /\((\d\d\d)\) (\d\d\d)-(\d\d\d\d)/.exec(cell)) ||
    (cell_parts = /(\d\d\d)-(\d\d\d)-(\d\d\d\d)/.exec(cell))     ||
    (cell_parts = /(\d\d\d)(\d\d\d)(\d\d\d\d)/.exec(cell))       ||
    (cell_parts = ['','','',''])

It's pretty short, no?

What's nice about it is that it parses several formats, but doesn't collapse all these possibilities into a single regex. Normally, you'd do that, but, that makes maintenance a headache. These regexes are simple.

The structure is also very short and simple. Typically, people do lines like this: reg=/foo/; reg.exec(str);. There's no need to define the regex into a variable. Just use it as a constant.

People also use if {...} else if {...}...., but there's a trick from Unix shell scripting that can cut that down. The OR boolean, ||, evaluates from left to right, and returns true on the first subexpression that returns true.

Regex.exec() returns false on non-matches, and an array on matches. The array evaluates to true. The assignment operator, =, returns the value of the assignment.


This post complains about the CakePHP save() method. Cake isn't the only framework that combines INSERT and UPDATE into one operation based on the value of an "id" field. It always seems like a good idea, because all the setup code to mangle the data before each operation is identical.

The problem comes when you need to extend the model, and then need to distinguish between INSERT and UPDATE. For example, when you create a record, you may want to timestamp it with a creation time. But when you update it, you don't want to alter that time.

Maybe you want to do the opposite - where INSERT will enter a lot of data, but you want the UPDATE code to modify only a few fields. Generic code can potentially alter columns that you want to "protect".

The deeper I get into Cake, the more I feel like it (and Rails) approach to hiding SQL from the programmer isn't really a good thing. It's especially frustrating because SQL is a higher level language than PHP. So, you go through some mental acrobatics to set up the framework to produce the right SQL... and the SQL turns out to be a single SELECT or a SELECT with one or two JOINs. It's "kiddy SQL".


The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

8 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.