“Why I hate Criteria”

Nicking the title from the previous post, oh and the sentiment. I don’t hate Criteria**, it is actually quite good, however watching the video in the previous post reminded me of a few issues we have had in the office where we have complained about it or just got plain confused…

I know Dan, for example, doesn’t see the point of using Criteria because what is wrong with SQL?

I have sat and scratched my head a few times trying to figure out how to query using Criteria, I know how I would do it in SQL but I can sit for ages trying to bend Criteria to my will.

I really should have RTFM

We do still recommend that you use SQL when it proves to be simpler, though.

Criteria is great when it fits your needs, but when it doesn’t or becomes very complex..stop step back and use SQL.

Using Propel 1.3 you get to use PDO and that is not something that is framework specific it’s an inbuilt PHP database abstraction layer. So the skills you learn using PDO are transferable to another project that doesn’t use a framework but uses a database.

So we have a custom query that we want to run and get back a bunch of user objects and we really don’t want to use Criteria…easy:

$name = “Wards”;
$bunchofusers = array();
//Our highly complex query….
//Fancy prepared stuff you get from PDO…think sprintf
$stmt = $con->prepare(“SELECT * FROM user WHERE last_name = ?”);
$stmt->bindValue(1, $name);
//erm execute…
$stmt->execute();
//Loop on our rows…and lets make some User objects..
while($row = $stmt->fetch()) {
$oUser = new User();
$oUser->hydrate($row);
$bunchofusers[]=$oUser;
}

Nothing really new to learn in the above code, it’s more like remembering that we can code how we choose too and we don’t have to be shackled to a certain way or slowed down by a framework when things don’t exactly fit.

** “What is Criteria?” I hear you say…well it comes with the Propel ORM, and it is for building up queries using objects rather than SQL. We use Propel within the symfony framework as our current ORM of choice.

Reblog this post [with Zemanta]

Post a Comment

Your email address is never published nor shared. Required fields are marked *

Ready to talk?

Whether you want to create a new digital product or make an existing one even better, we'd love to talk it through.

Get in touch