Answer the question
In order to leave comments, you need to log in
A bit about ActiveRecords?
<?php
namespace core\base;
use core\libs\PdoSingleton;
use ReflectionObject;
abstract class Model
{
public $id;
abstract protected static function table();
public function __set($name, $value)
{
$this->$name = $value;
}
public static function findAll()
{
$pdo = PdoSingleton::getInstance();
$sql = 'select * from ' . static::table();
return $pdo->query($sql, [], static::class);
}
public static function findOneById($id)
{
$pdo = PdoSingleton::getInstance();
$sql = 'select * from ' . static::table() . ' where id = :id';
$result = $pdo->query($sql, [':id' => $id], static::class);
return $result ? $result[0] : null;
}
public static function findOneByColumn($column, $value)
{
$pdo = PdoSingleton::getInstance();
$sql = 'select * from ' . static::table() . ' where ' . $column . ' = :value limit 1';
$result = $pdo->query($sql, [':value' => $value], static::class);
return $result ? $result[0] : null;
}
private function mapPropertiesToDbFormat()
{
$reflector = new ReflectionObject($this);
$properties = $reflector->getProperties();
$mapped_properties = [];
foreach ($properties as $property) {
$property_name = $property->getName();
$mapped_properties[$property_name] = $this->$property_name;
}
return $mapped_properties;
}
public function save()
{
$pdo = PdoSingleton::getInstance();
$mapped_properties = $this->mapPropertiesToDbFormat();
$columns_to_params = [];
$params_to_values = [];
$index = 1;
foreach ($mapped_properties as $column => $value) {
$param = ':param' . $index;
$columns_to_params[] = $column . ' = ' . $param;
$params_to_values[':param' . $index] = $value;
$index++;
}
if ($this->id) {
$sql = 'update ' . static::table() . ' set ' . implode(', ', $columns_to_params) . ' where id = ' . $this->id;
$pdo->query($sql, $params_to_values, static::class);
} else {
$sql = 'insert into ' . static::table() . ' set ' . implode(', ', $columns_to_params);
$pdo->query($sql, $params_to_values, static::class);
$this->id = $pdo->getLastInsertId();
}
}
public function delete()
{
$pdo = PdoSingleton::getInstance();
$sql = 'delete from ' . static::table() . ' where id = :id';
$pdo->query($sql, [':id' => $this->id]);
$this->id = null;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question