全局添加与更新数据的方法

浏览:1141 发布日期:2015/07/01 分类:技术分享
添加与更新数据,常常会用到自动完成,自动验证,自动令牌,为此,我封装了一个全局模型类,在它里面封装了insert 与update方法,只要实例化这个类,就要吧方便更新数据库
    public function insert($data='', $options=array(), $replace=false){
        $options['type'] = 'insert';
        return $this->_write($data, $options, $replace);
    }
    
    public function update($data='', $options=array()){
        $options['type'] = 'update';
        return $this->_write($data, $options, $replace);
    }

    /**
     * 写入数据库
     * @param string $data
     * @param unknown $options
     * @param string $replace
     */
    protected function _write($data='', $options=array(), $replace=false){
    
        //自动完成
        if(isset($options['auto'])){
            $this->_auto = $options['auto']; unset($options['auto']);
        }
        //自动验证
        if(isset($options['validate'])){
            $this->_validate = $options['validate']; unset($options['validate']);
        }
        //自动令牌
        if(C('TOKEN_ON') && !empty($data)){
            $token = C('TOKEN_NAME', null, '__hash__'); $data[$token] = $_POST[$token];
        }
        
        $type = ($options['type'] == 'insert')? self::MODEL_INSERT : self::MODEL_UPDATE;
        unset($options['type']);
        if($this->create($data, $type)){
            if($type == self::MODEL_INSERT){
                $result = $this->add('', $options, $replace);
            }else{
                $result = $this->save('', $options);
            }
        }
        if($result){
            $return = array('status'=>1, 'result'=>$result);
        }else{
            $return = array('status'=>-1, 'error'=>$this->error);
        }
        return $return;
        
    }
最佳答案
评论( 相关
后面还有条评论,点击查看>>