2009年2月20日星期五

[fw-db] question about model patterns / best practices

In general, I use a set of model classes that return either a single associative array or an array of associative arrays such as:
 <?php
  class Game extends Zend_DB_Table{

         public function getGames(){
              $sql="select g.*, a.name as author_name from games g, authors a where g.author_id=a.id";
              $result=$this->_db->fetchAll($sql);
              return $result;
        }

  }
 
  I'd like to move towards returning objects such as the following (haven't tested, just writing off top off my head):

 <?php
  class Game extends Zend_DB_Table{

        private function _createObject($arr){
            $this->name=$arr['name'];
            $this->id=$arr['id'];
            $this->author_name=$arr['author_name']
            return $this;
        }

         public function getGames(){
              $sql="select g.*, a.name from games g, authors a where g.author_id=a.id";
              $result=$this->_db->fetchAll($sql);
              foreach($result as $row){
                   $obj_result=$this->createObject($row);
              }
              return $obj_result;
        }

  }

 A couple of questions:
1. I'd like to maintain as small as a number of classes as possible. The above seems problematic because I'd be returning the _db information which I'd prefer not to. It also seems to not be totally clear what a game is. Is it a list of games, a single game, or just an access point to get games. So assuming I can live with the problems of the second concern, how would I prevent the _db object from being exposed via a print_r statement?
2. A better design would seem to be to have 3 model classes. 1. a GameSingle model which would return a single row 2. a GameList model which would return an array of Game objects 3. a Game object which would basically do the $game->createObject() functionality and any associated functionality. Is that the appropriate way to handle this?


I'm pretty happy just returning an associative arrays but was thinking about how I would migrate this without creating too many classes. At a minimum, it seems like I would need a way to decouple my Game object from the database access class.

thanks for any help / info.


没有评论: