Working on a particular application, I keep writing very similar queries, again and again. They’re not exactly the same, but are of very similar form, and embedded in almost identical chunks of code, e.g.,
$Mysqli = new mysqli; if ($Stmt = $Mysqli->prepare('SELECT foo FROM tblFoo WHERE something = ?')) { $Stmt->bind_param('s', $this->_something); $Stmt->execute(); if (0 != $Stmt->errno) throw new Exception('blah, blah, blah'); $Stmt->bind_result($foo); while ($Stmt->fetch()){ $this->_foos[] = new Foo($foo); } $Stmt->close(); } else { throw new Exception('blah, blah, blah');); } }
and later, somewhere else …
$Mysqli = new mysqli; if ($Stmt = $Mysqli->prepare('SELECT bar, baz FROM tblBar WHERE somethingElse = ?')) { $Stmt->bind_param('s', $this->_somethingElse); $Stmt->execute(); if (0 != $Stmt->errno) throw new Exception('blah, blah, blah'); $Stmt->bind_result($bar, $baz); while ($Stmt->fetch()){ // do something else with $bar and $baz } $Stmt->close(); } else { throw new Exception('blah, blah, blah');); } }
… and then another, and elsewhere another … etc.
Is this a real violation of DRY? It doesn’t seem to make sense to write a class for performing this kind of query (with constructor params or setters for table, column, bound variables, etc.) and then reusing it throughout my app. But at the same time, I can’t shake this nagging feeling that I’m repeating myself.
Maybe it’s just that there are only so many ways to write a simple query and that a certain amount of repetition like this is to be expected.
Thoughts?
A lot of people do exactly this. Create a class representing each table, that all inherit from the same class. The base class can handle loading and saving the data. So if you want to load the data, you just call the load method. And you can set and access the field values by the properties of the objects.
There’s also libraries like hibernate that handle a lot of the dirty work for you.