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.