HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Php/Doctrine array hydration

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayphpdoctrinehydration

Problem

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?

Solution

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
  ));
}

Code Snippets

foreach ( $p['PostComment'] as $comment )
{
  $comment = (object) $comment;
  $this->Controls->Add( new CommentPanel(
      $comment->text
    , $comment->User->nickname
    , $comment->last_updated_ts
  ));
}

Context

StackExchange Code Review Q#222, answer score: 5

Revisions (0)

No revisions yet.