WordPress: creare una classe per gestire il database

WordPress: creare una classe per gestire il database

Possiamo semplificare le operazioni di lettura e scrittura sul database di WordPress creando una classe che utilizzi i metodi standard di WordPress.

La classe è la seguente:


class My_DB {
	const PREFIX = 'my_'; // Il prefisso scelto per le tabelle
	
	/** @returns Bool **/

	public static function insert( $table, $data, $format ) {
		global $wpdb;
		$table_name = self::PREFIX . $table;
		return $wpdb->insert( $table_name, $data, $format );
	}

	/** @returns Object or null **/

	public static function getResults( $query ) {
		global $wpdb;
		return $wpdb->get_results( $query );
	}

	/** @returns Var or null **/

	public static function getResult( $query ) {
		global $wpdb;
		return $wpdb->get_var( $query );
	}

    /** @returns Integer or Boolean **/

	public static function update( $table, $data, $where, $format = null, $where_format = null ) {
		global $wpdb;
		$table_name = self::PREFIX . $table;
		return $wpdb->update( $table_name, $data, $where, $format, $where_format );
	}

	 /** @returns Integer or Boolean **/

	public function deleteRow( $table, $where, $where_format = null ) {
		global $wpdb;
		$table_name = self::PREFIX . $table;
		return $wpdb->delete( $table_name, $where, $where_format );
	}
}

Torna su