У меня пока что получилось вот так
сам класс AR
namespace Core\Db;
use Core\Db\DBConnect;
class Model
{
public $table;
protected $fields = [];
protected $properties = [];
private $_conn = null;
public function __construct()
{
$dbConfig = require 'core/database.php';
$getInstance = DBConnect::getInstance($dbConfig);
$this->_conn = $getInstance->getConnection();
$className = strtolower(get_class($this));
$temp_tbname = str_replace('models\\', '', $className);
$this->table = strtolower($temp_tbname);
$this->getColumnName();
}
public function __set($name, $value)
{
$this->properties[$name] = $value;
}
public function __get($name)
{
if (array_key_exists($name, $this->fields)) {
return $this->properties[$name];
}
}
private function getColumnName()
{
foreach($this->_conn->query("SHOW COLUMNS FROM users") as $column)
{
if($column['Extra'] != 'auto_increment')
$this->fields[] = $column['Field'];
}
return $this->fields;
}
public function save()
{
$bindParamNames = [];
foreach($this->fields as $field)
{
$bindParamNames[] = ":". $field;
}
var_dump($bindParamNames);
$fields = implode(', ', $this->fields);
$bindParamNamesString = implode(', ', $bindParamNames);
$stmt = $this->_conn->prepare("INSERT INTO " . $this->table . " (" . $fields. ") VALUES (" . $bindParamNamesString . ")");
foreach($bindParamNames as $param)
{
$key = str_replace(':', '', $param);
$stmt->bindParam($param, $this->properties[$key]);
}
$stmt->execute();
}
}
Класс User наследует Model
namespace Models;
use Core\Db\Model;
class Users extends Model
{
}
Пример
use Models\Users;
$user = new Users();
$user->email = 'google@gmail.com';
$user->name = "User88";
$user->save();
Класс сохранять в бд данные, но я совсем не увернь что реализовал паттерн ActiveRecord. Или все такие какой-то степени реализация AR есть ?