WordPress: ORM Model Class

WordPress: ORM Model Class

Object Relational Mapping or ORM is something that WordPress is missing, but that doesn’t mean we can’t create an abstract Model that act similar to ORM behavior.

Here are the first version to implement the ORM in WordPres – far from completions.

<?php 

abstract class Model {

	static $table_name = '';

	public static function table() {
		global $wpdb;

		return $wpdb->prefix.static::$table_name;
	}
	
	public static function all($conditions = '') {

		if(!empty(self::table())) {
			global $wpdb;

			$sql = "SELECT * FROM ".self::table() . $conditions;

			return $wpdb->get_results($sql);
		}

		return false;
	}

	public function row($conditions = '') {

		if(!empty(self::table())) {
			global $wpdb;

			$sql = "SELECT * FROM ".self::table() . $conditions;

			return $wpdb->get_row($sql);
		}

		return false;
	}

	public function findById($id) {
		global $wpdb;

		$sql = "SELECT * FROM ".self::table() . " WHERE id = '".$id."'";

		return $wpdb->get_row($sql);
	}

	public static function find($type, $parameters) {
		if(empty($type)) {
			$type = 'all';
		}

		$conditions = isset($parameters['conditions']) ? (' WHERE ' . join(' AND ',$parameters['conditions'])) : null;

		if($type == 'all') {
			return self::all($conditions);
		} else if($type == 'row') {
			return self::row($conditions);
		}

		return false;
	}

	public static function create($data) {
		global $wpdb;

		if($wpdb->insert(self::table(),$data)) {
			$id = $wpdb->insert_id;

			$data = self::findById($id);

			return $data;	
		}

		return false;		
	}

	public static function update($data, $where, $format = null, $where_format = null) {
		global $wpdb;

		return $wpdb->update( self::table(), $data, $where, $format, $where_format );
	}

	public static function delete($data) {
		global $wpdb;

		return $wpdb->delete( self::table(), $data );	
	}
}

Here are the implementation:

<?php

// make sure to include the abstract class first before extending the Model Class

class State extends Model {
	static $table_name = 'states';
}

The usage:

<?php

// include the State class in your plugin first

$states = State::all(); // fetch all available states
$state = State::findById(1); // find state with id = 1
$deleted = State::delete(['id' => 1]); // delete state record with id = 1

More features to add in – to have columns properties, what to hide, what to show, column alias and many more. But this is my first attempt to make the WordPress Plugin Development much easier (an attempt to replicate any famous PHP framework such Laravel, CakePHP and so on. Prefer to have something like Eloquent ORM)

Leave a Reply

Your email address will not be published. Required fields are marked *

fourteen − eight =