Building an OOP SQL query builder
PHP 7 implements something called a context sensitive lexer. What this means is that words that are normally reserved can be used if the context allows. Thus, when building an object-oriented SQL builder, we can get away with using methods named and
, or
, not
, and so on.
How to do it...
We define a
Application\Database\Finder
class. In the class, we define methods that match our favorite SQL operations:namespace Application\Database; class Finder { public static $sql = ''; public static $instance = NULL; public static $prefix = ''; public static $where = array(); public static $control = ['', '']; // $a == name of table // $cols = column names public static function select($a, $cols = NULL) { self::$instance = new Finder(); if ($cols) { self::$prefix = 'SELECT ' . $cols . ' FROM ' . $a; } else { self::$prefix = 'SELECT * FROM ' . $a; } return self::$instance; } ...