2009年2月21日星期六

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

YOu are using the functions on the db adapter.

If you use the classes functions (find(), fetchAll(), fetchRow()), they all return objects of Zend_Db_Table_Row. Look through the reference guide http://framework.zend.com/manual/en/zend.db.table.html

Shawn

On Feb 20, 2009, at 10:22 AM, water wrote:

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.




没有评论: