Zend Framework: Proper way to interact with database?

后端 未结 3 1297
孤独总比滥情好
孤独总比滥情好 2021-02-02 02:17

I\'m fairly new to the Zend Framework and MVC and I\'m a bit confused by Zend_DB and the proper way to interact with the database.

I\'m using the PDO MySQL adapter and h

3条回答
  •  耶瑟儿~
    2021-02-02 02:39

    Using Zend_Db you probably don't want to get into the details of prepared statements and the like. You just want to use the model objects to do basic CRUD (Create, Read, Update and Delete). I know the Programmer's Reference Guide is extensive, but its a great introduction to Zend_Db. You may want to take a closer look at the Zend_Db_Table documentation.

    But to give a quick answer to your question. Unless you need to override some default behavior you shouldn't need to extend the Zend_Db_Table_Row_Abstract. Also you can probably simplify the Users class to just be:

    class Users extends Zend_Db_Table_Abstract {
      protected $_name = 'users';
    
      // Code here
    }
    

    Then to use it you would do some of things you mentioned using the following:

    //Create a Users Model Object
    $usersDb = new Users();
    
    //Find the record with user_id = 4 and print out their name
    $row = $usersDb->find(4);
    echo $row->first_name . ' ' . $row->last_name
    
    //Change the first name of this user to Brian    
    $row->first_name = 'Brian';
    $row->update();
    
    //Insert a user into the database
    $data = array(
      'first_name' => 'Gilean',
      'last_name' => 'Smith');
    $usersDb->insert($data);
    
    //Retrieve all users with the last name smith and print out their full names
    $rows = $usersDb->fetchAll($usersDb->select()->where('last_name = ?', 'smith'));    
    foreach ($rows as $row) {
      echo $row->first_name . ' ' . $row->last_name
    }
    

提交回复
热议问题