According to the Doctrine docs, you should use Array hydration rather than record hydration when retrieving data for read-only purposes.
Unfortunately, this means I have to use array syntax (as opposed to object syntax) to reference the data.
$q = Doctrine_Query::create()
->from('Post p')
->leftJoin('p.PostComment pc')
->leftJoin('pc.User u')
->where('p.post_id = ?', $id);
$p = $q->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY);
...
foreach ($p['PostComment'] as $comment) {
$this->Controls->Add(new CommentPanel($comment['text'],
$comment['User']['nickname'],
$comment['last_updated_ts']));
}
Maybe it's just me, but all of those string literals as array indexes are kinda scary. Does anyone have some ideas for cleaning this up?
1 Answer 1
Scary? In what way? I don't really get that.
It's just syntax. If you really care, just cast the arrays as stdClass objects
foreach ( $p['PostComment'] as $comment )
{
$comment = (object) $comment;
$this->Controls->Add( new CommentPanel(
$comment->text
, $comment->User->nickname
, $comment->last_updated_ts
));
}
-
\$\begingroup\$ He'd need to cast User to an object too, else it would be $comment->User["nickname"]; But yeah, casting it was also in my mind \$\endgroup\$edorian– edorian2011年01月27日 08:38:28 +00:00Commented Jan 27, 2011 at 8:38
-
\$\begingroup\$ I guess I'm just used to other languages where a typo in a literal would not be caught until run time but a typo in a property name would be caught at compile time. But with a scripting language like PHP both will not be noticed until run time. \$\endgroup\$BenV– BenV2011年01月27日 14:47:18 +00:00Commented Jan 27, 2011 at 14:47
-
2\$\begingroup\$ If that's the concern, you could use define()s or constants to reference your fields, rather than string literals. But that's probably only making things worse. Object hydration may take a little more time and memory but unless you have problems with either, I'd still use it for the very reason you outline here. \$\endgroup\$lotsoffreetime– lotsoffreetime2011年01月27日 20:53:38 +00:00Commented Jan 27, 2011 at 20:53
$comment->text;
\$\endgroup\$