代码之家  ›  专栏  ›  技术社区  ›  Dr Casper Black

类表映射器设计PHP和ZF

  •  0
  • Dr Casper Black  · 技术社区  · 15 年前

    有没有更好的方法来使用ZF使用映射器、现实生活对象和表对象?

    这就是我如何使用Zend框架:

    class User_DbTable extends Zend_DB_Table_Abstract{
          protected $_name = "user"; // name of the table
    }
    

    用户类->用户对象:

    class User{
      protected $_id;
      protected $_name;
      protected $_addresses; //list of OBJs
    
      public function set_name($_name){
        $this->_name = $_name;
      }
      public function get_name(){
        return $this->_name;
      }
      public function set_adresses($_addresses){
        $this->_addresses = $_addresses;
      }
    // and so on....
    }
    

    映射器:

    class UserMapper{
       protected $userTBL;
    
       public function __construct(){
         $this->userTBL = new User_DbTable();
       }
       public function __fatchAll(){
         $select = $this->userTBL->select();
         foreach($this->userTBL->fetchAll($select) as $row){
           $user = new User(); // model
           $user->set_name($row->name);
           // gat all the addreses of this user with eg. AddressMapper()
           $user->set_addresses($addresses); // array of object of address just like User
           $users[] = $user;
         }
         return $users;
       }
    }
    

    在控制器中的用法: 列表动作:

    $userMP = new UserMapper();
    $this->view->users = $userMP->__fatchAll();
    

    或添加/保存操作:

    $newUser = new User();
    $newUser->set_name('somename');
    $userMP = new UserMapper();
    $userMP->save($newUser);
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Juan    15 年前

    ZF允许您扩展 Zend_Db_Table_Row 类,并告诉Zend_db_table类始终使用它。这样,您就可以访问 zend_db_table_行 功能,同时在顶部添加您自己的逻辑。

    你可以这样做

    class User_DbTable extends Zend_DB_Table_Abstract{
          protected $_name = "user"; // name of the table
          protected $_rowClass = "User"; // The name of your Zend_Db_Table_Row class
    }
    
    class User extends Zend_Db_Table_Row {
    
      public function set_name($_name){
        $this->name = $_name;
      }
      public function get_name(){
        return $this->name;
      }
      public function set_adresses($_addresses){
        $this->addresses = $_addresses;
      }
    // and so on....
    }
    

    你可以看到更多关于 zend_db_table_行 here