Allow change from on ModelMySQL.

This commit is contained in:
kj 2020-03-27 10:25:40 -04:00
parent f6c82c7a8c
commit 2d377eb803

View File

@ -42,7 +42,7 @@ class ModelMySQL {
*
* @return mysqli
*/
private static function db(){
private static function db() {
if (is_null(static::$db))
static::$db = Database::getConnection();
@ -61,11 +61,11 @@ class ModelMySQL {
* @return mysqli_result
* Contiene el resultado de la llamada SQL.
*/
private static function query($query){
private static function query($query) {
$db = static::db();
$result = $db->query($query);
if ($db->errno){
if ($db->errno) {
echo '<style>body{white-space: pre-line;}</style>';
throw new \Exception(
"\nFallo al consultar la base de datos\n" .
@ -81,16 +81,17 @@ class ModelMySQL {
/*
* Reinicia la configuración de la sentencia SQL.
*/
private static function resetQuery(){
private static function resetQuery() {
static::$querySelect = [
'select' => '*',
'where' => '',
'from' => '',
'leftJoin' => '',
'rightJoin' => '',
'innerJoin' => '',
'AndOr' => '',
'orderBy'=>'',
'groupBy'=>'',
'orderBy' => '',
'groupBy' => '',
'limit' => '',
];
}
@ -102,38 +103,44 @@ class ModelMySQL {
* @return string
* Contiene la sentencia SQL.
*/
private static function buildQuery(){
$sql = 'SELECT '.static::$querySelect['select'].' FROM '.static::table();
private static function buildQuery() {
$sql = 'SELECT '.static::$querySelect['select']:
if (static::$querySelect['leftJoin'] != ''){
if (static::$querySelect['from'] != '') {
$sql .= ' FROM '.static::$querySelect['from'];
} else {
$sql .= ' FROM '.static::table();
}
if (static::$querySelect['leftJoin'] != '') {
$sql .= static::$querySelect['leftJoin'];
}
if(static::$querySelect['rightJoin'] != ''){
if(static::$querySelect['rightJoin'] != '') {
$sql .= static::$querySelect['rightJoin'];
}
if(static::$querySelect['innerJoin'] != ''){
if(static::$querySelect['innerJoin'] != '') {
$sql .= static::$querySelect['innerJoin'];
}
if (static::$querySelect['where'] != ''){
if (static::$querySelect['where'] != '') {
$sql .= ' WHERE '.static::$querySelect['where'];
if (static::$querySelect['AndOr'] != ''){
if (static::$querySelect['AndOr'] != '') {
$sql .= static::$querySelect['AndOr'];
}
}
if (static::$querySelect['groupBy'] != ''){
if (static::$querySelect['groupBy'] != '') {
$sql .= ' GROUP BY '.static::$querySelect['groupBy'];
}
if (static::$querySelect['orderBy'] != ''){
if (static::$querySelect['orderBy'] != '') {
$sql .= ' ORDER BY '.static::$querySelect['orderBy'];
}
if (static::$querySelect['limit'] != ''){
if (static::$querySelect['limit'] != '') {
$sql .= ' LIMIT '.static::$querySelect['limit'];
}
@ -152,11 +159,11 @@ class ModelMySQL {
* @return ModelMySQL
* Retorna un objeto de la clase actual.
*/
public function getInstance($elem = []){
public function getInstance($elem = []) {
$class = get_called_class();
$instace = new $class;
foreach ($elem as $key => $value){
foreach ($elem as $key => $value) {
$instace->$key = $value;
}
@ -167,14 +174,14 @@ class ModelMySQL {
* @return array
* Contiene los atributos indexados del objeto actual.
*/
private function getVars(){ // Source: https://stackoverflow.com/questions/10009015/show-all-public-attributes-name-and-value-of-an-object
private function getVars() { // Source: https://stackoverflow.com/questions/10009015/show-all-public-attributes-name-and-value-of-an-object
$get_vars_proxy = create_function('$obj', 'return get_object_vars($obj);');
$result = $get_vars_proxy($this);
foreach ($this->ignoreSave as $del){
foreach ($this->ignoreSave as $del) {
unset($result[$del]);
}
foreach ($this->forceSave as $value){
foreach ($this->forceSave as $value) {
$result[$value] = $this->$value;
}
@ -185,7 +192,7 @@ class ModelMySQL {
* @return string
* Devuelve el nombre de la clase actual
*/
public static function className(){
public static function className() {
return strtolower(substr(strrchr(get_called_class(), '\\'), 1));
}
@ -196,7 +203,7 @@ class ModelMySQL {
*
* @return string
*/
private static function table(){
private static function table() {
if (isset(static::$table))
return static::$table;
return static::className().static::$tableSufix;
@ -205,10 +212,10 @@ class ModelMySQL {
/*
* Actualiza los valores en la BD con los valores del objeto actual
*/
private function update(){
private function update() {
$atts = $this->getVars();
foreach ($atts as $key => $value){
foreach ($atts as $key => $value) {
$value = static::db()->real_escape_string($value);
$set[]="$key='$value'";
}
@ -224,11 +231,11 @@ class ModelMySQL {
* Inserta una nueva fila en la base de datos a partir del
* objeto actual.
*/
private function add(){
private function add() {
$db = static::db();
$atts = $this->getVars();
foreach ($atts as $key => $value){
foreach ($atts as $key => $value) {
$into[] = "`$key`";
$values[] = "'".$db->real_escape_string($value)."'";
}
@ -245,7 +252,7 @@ class ModelMySQL {
* Revisa si el objeto a guardar es nuevo o no y según el resultado
* llama a update para actualizar o add para insertar una nueva fila.
*/
public function save(){
public function save() {
$pk = $this->primaryKey;
if (isset($this->$pk))
$this->update();
@ -256,10 +263,10 @@ class ModelMySQL {
/*
* Elimina el objeto actual de la base de datos.
*/
public function delete(){
public function delete() {
$atts = $this->getVars();
foreach ($atts as $key => $value){
foreach ($atts as $key => $value) {
$value = static::db()->real_escape_string($value);
$set[]="$key='$value'";
}
@ -277,10 +284,10 @@ class ModelMySQL {
* @param array $columns
* Columnas que se selecionarán en la consulta SQL.
*/
public static function select($columns){
public static function select($columns) {
$db = static::db();
$select = [];
foreach($columns as $column){
foreach($columns as $column) {
$select[] = $db->real_escape_string($column);
}
@ -289,6 +296,24 @@ class ModelMySQL {
return new static();
}
/*
* Define FROM en la sentencia SQL.
*
* @param array $tables
* Tablas que se selecionarán en la consulta SQL.
*/
public static function from($tables) {
$db = static::db();
$from = [];
foreach($tables as $table) {
$from[] = $db->real_escape_string($table);
}
static::$querySelect['from'] = join(', ', $from);
return new static();
}
/*
* Define el WHERE en la sentencia SQL.
*
@ -305,8 +330,8 @@ class ModelMySQL {
* - static::where(columna, operador, valor)
* - static::where(columna, valor) // Operador por defecto "="
*/
public static function where($column, $operator, $value=null){
if (is_null($value)){
public static function where($column, $operator, $value=null) {
if (is_null($value)) {
$value = $operator;
$operator = '=';
}
@ -330,8 +355,8 @@ class ModelMySQL {
* @param boolean $in
* Define si se usará IN o NOT IN en la sentencia SQL.
*/
public static function where_in($column,$arr, $in = true){
foreach($arr as $index => $value){
public static function where_in($column,$arr, $in = true) {
foreach($arr as $index => $value) {
$arr[$index] = static::db()->real_escape_string($value);
}
@ -362,8 +387,8 @@ class ModelMySQL {
* - static::leftJoin(tabla,columnaA, operador, columnB)
* - static::leftJoin(tabla,columnaA, columnB) // Operador por defecto "="
*/
public static function leftJoin($table, $columnA, $operator, $columnB = null){
if (is_null($columnB)){
public static function leftJoin($table, $columnA, $operator, $columnB = null) {
if (is_null($columnB)) {
$columnB = $operator;
$operator = '=';
}
@ -396,8 +421,8 @@ class ModelMySQL {
* - static::rightJoin(tabla,columnaA, operador, columnB)
* - static::rightJoin(tabla,columnaA, columnB) // Operador por defecto "="
*/
public static function rightJoin($table, $columnA, $operator, $columnB = null){
if (is_null($columnB)){
public static function rightJoin($table, $columnA, $operator, $columnB = null) {
if (is_null($columnB)) {
$columnB = $operator;
$operator = '=';
}
@ -429,8 +454,8 @@ class ModelMySQL {
* - static::innerJoin(tabla,columnaA, operador, columnB)
* - static::innerJoin(tabla,columnaA, columnB) // Operador por defecto "="
*/
public static function innerJoin($table, $columnA, $operator, $columnB = null){
if (is_null($columnB)){
public static function innerJoin($table, $columnA, $operator, $columnB = null) {
if (is_null($columnB)) {
$columnB = $operator;
$operator = '=';
}
@ -460,8 +485,8 @@ class ModelMySQL {
* - static::and(columna, valor) // Operador por defecto "="
* - static::and(columna, valor)->and(columna, valor)->and(columna, valor) // anidado
*/
public static function and($column, $operator, $value=null){
if (is_null($value)){
public static function and($column, $operator, $value=null) {
if (is_null($value)) {
$value = $operator;
$operator = '=';
}
@ -490,8 +515,8 @@ class ModelMySQL {
* - static::or(columna, valor) // Operador por defecto "="
* - static::or(columna, valor)->or(columna, valor)->or(columna, valor) // anidado
*/
public static function or($column, $operator, $value=null){
if (is_null($value)){
public static function or($column, $operator, $value=null) {
if (is_null($value)) {
$value = $operator;
$operator = '=';
}
@ -509,12 +534,12 @@ class ModelMySQL {
* @param array $arr
* Columnas por las que se agrupará.
*/
public static function groupBy($arr){
public static function groupBy($arr) {
static::$querySelect['groupBy'] = join(', ', $arr);
return new static();
}
public static function limit($initial, $final = 0){
public static function limit($initial, $final = 0) {
$initial = (int)$initial;
$final = (int)$final;
@ -536,8 +561,8 @@ class ModelMySQL {
* Define si el orden será de manera ascendente (ASC),
* descendente (DESC) o aleatorio (RAND).
*/
public static function orderBy($value, $order = 'ASC'){
if ($value == "RAND"){
public static function orderBy($value, $order = 'ASC') {
if ($value == "RAND") {
static::$querySelect['orderBy'] = 'RAND()';
return new static();
}
@ -557,7 +582,7 @@ class ModelMySQL {
*
* @return int
*/
public static function count(){
public static function count() {
static::$querySelect['select'] = 'count(*) as quantity';
$sql = static::buildQuery();
$result = static::query($sql)->fetch_assoc();
@ -570,7 +595,7 @@ class ModelMySQL {
* @param int $id
* @return ModelMySQL
*/
public static function getById($id){
public static function getById($id) {
return static::where('id', $id)->getFirst();
}
@ -583,8 +608,8 @@ class ModelMySQL {
* @param array $in
* Columnas en las que se va a buscar (null para buscar en todas)
*/
public static function search($search, $in = null){
if ($in == null){
public static function search($search, $in = null) {
if ($in == null) {
$className = get_called_class();
$objAtts = array_keys((new $className())->getVars());
}
@ -595,7 +620,7 @@ class ModelMySQL {
$where = [];
foreach($in as $row){
foreach($in as $row) {
$where[] = "$row LIKE '%$search%'";
}
@ -612,13 +637,13 @@ class ModelMySQL {
*
* @return ModelMySQL[]
*/
public static function get(){ // Devuelve array vacío si no encuentra nada
public static function get() { // Devuelve array vacío si no encuentra nada
$sql = static::buildQuery();
$result = static::query($sql);
$instaces = [];
while ($row = $result->fetch_assoc()){
while ($row = $result->fetch_assoc()) {
$instaces[] = static::getInstance($row);
}
@ -631,7 +656,7 @@ class ModelMySQL {
* @return mixed
* Puede retornar un objeto ModelMySQL o null.
*/
public static function getFirst(){ // Devuelve null si no encuentra nada
public static function getFirst() { // Devuelve null si no encuentra nada
static::limit(1);
$instaces = static::get();
return empty($instaces) ? null : $instaces[0];
@ -642,14 +667,14 @@ class ModelMySQL {
*
* @return ModelMySQL[]
*/
public static function all(){
public static function all() {
$sql = 'SELECT * FROM '.static::table();
$result = static::query($sql);
$instaces = [];
while ($row = $result->fetch_assoc()){
while ($row = $result->fetch_assoc()) {
$instaces[] = static::getInstance($row);
}