Skip to content

Commit

Permalink
Upgraded Model to feel more like an ORM with improved performance and…
Browse files Browse the repository at this point in the history
… use cases
  • Loading branch information
aymenBenadra committed Apr 8, 2022
1 parent b8b349c commit 2d6c4ae
Showing 1 changed file with 81 additions and 10 deletions.
91 changes: 81 additions & 10 deletions core/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Core;

use Exception;

/**
* Model Class
* - Initialize the database connection
Expand All @@ -17,21 +19,58 @@ abstract class Model
{
protected $db;
protected $table;

protected $schema;

/**
* Initialize the database connection
* Initialize the database connection and set schema of the table
*
* @return void
*/
public function __construct()
public function __construct($schema)
{
$this->db = new Database;
$this->schema = $schema;
}

/**
* Return schema of the table
*
* @param ?array $fields
* @return array
* @throws Exception
*/
public function getSchema(...$fields)
{
if ($fields) {
$schema = [];
foreach ($fields as $field) {
if (array_key_exists($field, $this->schema)) {
$schema[$field] = $this->schema[$field];
} else {
throw new Exception("Field $field does not exist in schema");
}
}
return $schema;
}
return $this->schema;
}

/**
* Return schema of required fields
*
* @return array
*/
public function getRequiredSchema()
{
return array_filter($this->schema, function ($value) {
return strpos($value, 'required') !== false;
});
}

/**
* Get single record from database
*
* @param mixed $id
* @param int $id
* @return object
*/
public function get($id)
Expand All @@ -40,7 +79,23 @@ public function get($id)
$this->db->bind(':id', $id);
return $this->db->single();
}


/**
* get record by field
*
* @param string $field
* @param mixed $value
* @return object
*/
public function getBy($field, $value)
{
$sql = "SELECT * FROM {$this->table} WHERE $field = :$field";
$this->db->query($sql);
$this->db->bind(":$field", $value);

return $this->db->single();
}

/**
* Get all records from database
*
Expand All @@ -51,7 +106,23 @@ public function getAll()
$this->db->query("SELECT * FROM $this->table");
return $this->db->resultSet();
}


/**
* Get all records by field
*
* @param string $field
* @param string $value
* @return array
*/
public function getAllBy($field, $value)
{
$sql = "SELECT * FROM {$this->table} WHERE $field = :$field";
$this->db->query($sql);
$this->db->bind(":$field", $value);

return $this->db->resultSet();
}

/**
* Add new record to database
*
Expand All @@ -75,7 +146,7 @@ function ($param) {

return $this->db->execute();
}

/**
* Update record in database
*
Expand All @@ -102,7 +173,7 @@ function ($param) {

return $this->db->execute();
}

/**
* Delete record from database
*
Expand All @@ -116,7 +187,7 @@ public function delete($id)

return $this->db->execute();
}

/**
* Get last inserted id
*
Expand Down

0 comments on commit 2d6c4ae

Please sign in to comment.