Thursday, January 22, 2015

Generic dao class for wordpress

metaDefinition = $metaDefinition;
        $this->tableName = $tableName;
    }
    /**
     * Insert a new row
     * @global type $wpdb
     * @param type $pairs
     * @return type last inserted id
     */
    function insertRow($pairs){
            global $wpdb;          
            $prototypes = array();
             foreach ($pairs as $colName => $dataType) {
                 $prototypes[] = $this->metaDefinition[$colName];
             }
            $wpdb->insert($this->tableName, $pairs,$prototypes);
            return $wpdb->insert_id;
    }
    /**
     * Select all rows
     * @global type $wpdb
     * @param type $orderingExpr
     * @param type $limit
     * @return type
     */
    function  selectAllRows($orderingExpr=" ",$limit=""){
            global $wpdb;
            $sql = "select * from $this->tableName ".$orderingExpr.$limit;
            return $wpdb->get_results($sql);
    }
    /**
     * Query table
     * @global type $wpdb
     * @param type $where
     * @param type $orderingExpr
     * @param type $limit
     * @return type
     */
    function  selectRows($where,$orderingExpr=" ",$limit=""){
            global $wpdb;
            $sql = "select * from $this->tableName where ".$where.' '.$orderingExpr.' '.$limit;
            return $wpdb->get_results($sql);
    }
    /**
     * Select rows count
     * @global type $wpdb
     * @return type
     */
    function selectRowsCount(){
            global $wpdb;
            $sql = "select count(*)as count from $this->tableName ";
            return $wpdb->get_results($sql);
    }
    /**
     * Delete row
     * @global type $wpdb
     * @param type $pairs array of paris (columns, new values)
     * @param type $where
     * @param type $whereFormat
     * @return type
     */
    function updateRow($pairs,$where,$whereFormat=array("%d")){
            global $wpdb;
             $prototypes = array();
             foreach ($pairs as $colName => $dataType) {
                 $prototypes[] = $this->metaDefinition[$colName];
             }
             return $wpdb->update( $this->tableName, $pairs, $where, $prototypes, $whereFormat );
    }
        
    function deleteRow($where,$whereFormat=array("%d")){
            global $wpdb;
            return $wpdb->delete( $this->tableName, $where,$whereFormat);
    }
    

}
?>

An implementation of this genric class is this little code:
Supposing that we have this table :
CREATE  TABLE IF NOT EXISTS `wordpress_categ_type_poste` (
  `ctgtp_id` INT NOT NULL AUTO_INCREMENT ,
  `ctgtp_lib` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`ctgtp_id`) )
ENGINE = InnoDB;
then an extension of this class can be
'%d','ctgtp_lib'=>'%s'),$wpdb->prefix . "categ_type_poste");
    }
  }
?>
once you have finished that class, it's recommended to build your service class exposing some or all functions of the dao class.

No comments:

Post a Comment