# Php/Doctrine array hydration

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?

• from what i understand if you would fetch an object you would to $comment->text; or would you do$comment->getText() ? (Not to familiar with the "old/current" doctrine ;) ) Jan 26 '11 at 10:03
• @edorian: It would be $comment->text; – BenV Jan 26 '11 at 14:16 • I believe you can use all three. Jan 26 '11 at 22:38 • I was trying to write a longer answer but it really bowls down to "cast to stdClass (and thats already said now) if you don't like it" but maybe i don't get your reasoning behind that looking "scary". The difference between -> and [''] shoudn't matter so much ? Jan 27 '11 at 8:40 ## 1 Answer 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 )); }  • 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 Jan 27 '11 at 8:38
• 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.
– BenV
Jan 27 '11 at 14:47
• 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. Jan 27 '11 at 20:53