Is SQL Statement Object overkill?

I have a SQL Statement object (or we can say ORM)…
It’s kinda like this below

<?php

class SQLStatement implements ISQLStatement {
	private $table;
	private $sql;

	public function __construct($table) {
		$this->setTable($table);
	}

	public function setTable($table) {
		$this->table = $table;
	}

	public function select(array $columns) {
		$sql = 'SELECT ';
		$columns = implode(',', $columns);
		$sql .= $columns;
		$sql .= "FROM $this->table";

		$this->sql = $sql;
		return $this;
	}

	/*
	 * Setting up INSERT sql statement
	 *
	 *  @param array $records The records to insert.The array keys must be the columns, and the array values must be the new values
	 */

	public function insert(array $records) {
		$columns = array_keys($records);
		$values = array_values($records);
		$sql = 'INSERT INTO ';
		$sql .= $this->table . '('. implode(',', $columns) . ')';
		$sql .= ' VALUES ' . '(' . implode(',', $values) . ')';

		$this->sql = $sql;
		return $this;
	}

	/*
	 * Setting up UPDATE sql statement
	 *
	 *  @param array $records The records to update. The array keys must be the columns, and the array values must be the new records
	 *  @param array $where The conditions to update. The array keys must be the columns, and the array values must be the value
	 */
	public function update(array $records) {
		$sql = 'UPDATE ';
		$sql .= $this->table;
		$sql .= ' SET ';
		$lastOffset = count($records) - 1;
		foreach ($records as $column => $record) {
			$sql .= "$column = $record";
			if ($record != $records[$last]) {
				$sql .= ', ';
			}
		}

		$this->sql = $sql;
		return $this;
	}

	public function delete() {
		$sql = 'DELETE FROM ' . $this->table;
		$this->sql = $sql;
		return $this;
	}

	public function where(array $where) {
		if (!isset($this->sql)) {
			throw new BadMethodCallException('You must use SELECT, INSERT, UPDATE, or DELETE first before where clause');
		}
		$where = ' WHERE ';
		$lastOffset = count($where) - 1;
		foreach ($where as $column => $value) {
			if (is_array($value)) {
				$where .= "$column IN (" . implode(',', $value) . ')';
			}
			else {
				$where .= "$column = $value";
			}
			if ($value != $where[$last]) {
				$where .= " AND ";
			}
		}

Is this overkill and bad practice ?
Is just a string enough and good ?

Sometimes, when implementing OOP and trying to get on the “right” track, I feel like killing so much performance, and having a very big code instead of a simple one.

Class you’ve showed above is just a helper that allows you to write less code to retrieve data from DB.

It depends. If you have only 2-3 queries in your project then of course things like that class will be overkill. But if you have to do hundreds of queries you’ll save serious amount of time with such helper.

You just should feel how each class will help you in future. The trick is to find balance.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.