0

Let's say I'm building feed of comments and need the comment data and user data of the author. Comments are represented by the Comment class. Users are represented by the User class. When pulling the comments, the $author member of Comment should be set to an instance of User (to keep all the info about the author).

class Comment {
   var $id;
   var $body;
   var $timestamp;
   var $etc;
   var $authorid;
   var $author; //(a 'user' instance)
   static function fromArray($members){ /*...*/ }
}
class User {
   var $id;
   var $username;
   var $haspicture;
   var $etc;
   static function fromArray($members){ /*...*/ }
}

How i'm doing it now...

The way i've been doing it so far is by joining the tables and only pulling the basic user data I need... and if any column names collide, I set an alias (field AS somethingelse). Here's the basic look:

$query = mysql_query('SELECT c.*, u.username AS author_username, u.haspicture AS author_haspicture FROM comments c JOIN user u ON u.id = c.authorid');
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)){
   $comment = Comment::fromArray($row);
}

To create $author... the Comment fromArray() method that's fed with each row looks like this:

static function fromArray($members){ 
    foreach($members as $field => $value){
        $this->$field = $value;
    }
    $this->author = User::fromArray(array(
        'id' => $row['authorid'],
        'username' => $row['author_username'],
        'haspicture' => $row['author_haspicture']
    ));
}

So here's my question:

Am I missing something? There's got to be a better way of doing it. This way seems so inflexible and prone to breaking when tables change or a User method changes and ends up needing a field that's not provided by the query. A separate query for each user can't be an option... can it?


(p.s. keep in mind that the User object is a bit more complex than that, and it has many more methods that are called later on when the comments are displayed. It can't be reasonably flattened and treated as an array. An OO setup is pretty necessary.)

brianreavis
  • 11,135
  • 3
  • 38
  • 50

1 Answers1

1

If I were you I'd take a look at some of the ORM tools that are around, there's a good roundup of those available for php here:

Good PHP ORM Library?

Community
  • 1
  • 1
Whisk
  • 3,117
  • 2
  • 27
  • 29
  • Using a ORM is the way to go in that situation imho. But be sure to not expect the PHP ORMs availabe at the moment to be on par with (N)Hibernate class ORM software known from Java or .NET. At least that is what my last impression was when testing ORM solutions in PHP. – Max Nov 01 '09 at 12:43