Zend framework $db->update result

前端 未结 3 823
礼貌的吻别
礼貌的吻别 2021-01-20 15:34

Zend_Db_Adapter::update() returns the number of rows affected by the update operation. What is best way to determine if the query was successful?



        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 16:13

    If you are just looking for a boolean return value, this solution is the best for handling success in the model:

    class Default_Model_Test extends Zend_Db_Table {

    public function updateTest($testId, $testData){
    
        try {
    
            $this->_db->update('test', $testData, array(
                'id = ?'        => $testId
            ));
    
            return true;
    
        }
        catch (Exception $exception){
    
            return false;
    
        }
    
    }
    

    }

    But, a better solution would be to handling success from the controller level, because it is making the request:

    class Default_Model_Test extends Zend_Db_Table {
    
        public function updateTest($testId, $testData){
    
            $this->_db->update('test', $testData, array(
                'id = ?'        => $testId
            ));
    
        }
    
    }
    
    class Default_TestController extends Zend_Controller_Action {
    
        public function updateAction(){
    
            try {
    
                $testId = $this->_request->getParam('testId');
                if (empty($testId)) throw new Zend_Argument_Exception('testId is empty');
    
                $testData = $this->_request->getPost();
                if (empty($testId)) throw new Zend_Argument_Exception('testData is empty');
    
                $testModel->updateTest($testId, $testData);
    
            }
            catch (Exception $exception){
    
                switch (get_class($exception)){
    
                    case 'Zend_Argument_Exception': $message = 'Argument error.'; break;
                    case 'Zend_Db_Statement_Exception': $message = 'Database error.'; break;
                    case default: $message = 'Unknown error.'; break;
    
                }
    
            }
    
        }
    
    }
    

    This is an excellent solution when working with multiple resource types, using a switch on the exception type, and doing what is appropriate based on your program's needs. Nothing can escape this vacuum.

提交回复
热议问题