Simplify Common PDO Tasks Without ORM: A Small Wrapper
Join the DZone community and get the full member experience.
Join For FreePHP frameworks are great. For data access, though, Vic Cherubini doesn't think so.
Specifically, Vic feels that using an ORM framework to write SQL just wrenches too much control out of the developer's hands, and ties said hands too tightly to one (not necessarily long-lived) ORM system. Excerpted, his objections come down to these:
Using an ORM feels clunky, slow, vendor-locked, and difficult to debug. Additionally, with any system of size, you are going to have to write some large SQL queries. I feel mixing ORM code and hand-written SQL is ugly...
I do not buy into the argument an ORM lets you switch databases easily. The ORM might facilitate that, but I have never worked on a project of any non-trivial size that after being put into production had its database changed. My fulltime job has a PostgreSQL database with 550+ tables, 220+ stored procedures, and 110 or so triggers. Migrating that to different database software would never happen.
And Vic isn't the only ORM nay-sayer.
In 2009 Josh Berkus gave a popular O'Relly webcast entitled 'Ten Ways to Wreck Your Database'. Wrecker #10? Runaway ORM.
Wikipedia has a vast entry on the problem of the object-relational impedance mismatch.
Arnon Rotem-Gal-Oz authored an even-handed cost/benefit analysis of the use of ORM in specific applications.
Even Hibernate's website discusses the mismatch problem, although as prolegomena to a fuller treatment of Hibernate's advantages.
It's worth noting that Vic doesn't object to ORM in principle, so the mapping itself doesn't locate his concern. Rather, he says, the practice of writing complex SQL is, at the moment, something ORM's just can't handle. (This parallels my experience with MSAccess, incidentally, even in relatively small (~100 tables) databases.)
But not all queries are that complex. And the PHP Data Object (PDO) syntax can sometimes get a little verbose for really basic querying. So instead of using ORM for the simple and hand-coding the complex -- a chemistry disaster waiting to happen -- Vic created a very small wrapper to make simple queries much easier.
Here's one of his wrapper functions:
public function fetch_all($query, $parameters=array()) { $read_stmt = $this->prepare_and_execute($query, $parameters); $fetched_rows = $read_stmt->fetchAll(\PDO::FETCH_CLASS); $read_stmt->closeCursor(); unset($read_stmt); return($fetched_rows); }
The rest of the code is freely available on his site, along with one example of a controller action that reads much more like scalar data access than like object-oriented anything. Definitely worth filing away for the future.
Opinions expressed by DZone contributors are their own.
Comments