Answer the question
In order to leave comments, you need to log in
Small implementation of ActiveRecord php?
I'm studying design patterns, so I would like to implement ActiveRecord, so I can't practice.
How to implement it
$user = new Users();
$user->name = 'Someone';
$user->save();
class AcitveRecord
{
protected $table;
public function save(){....}
}
class Users extends ActiveRecord
{
$this->table = 'Users';
}
Answer the question
In order to leave comments, you need to log in
I recommend before studying patterns:
1) read at least the php documentation to get acquainted with its capabilities
2) read at least briefly about SOLID and GRASP
3) and now study patterns.
php.net/manual/en/language.oop5.magic.php
How to find the fields of any table?
look at mine, maybe you will find something useful
https://github.com/ArtemRochev/ORM/blob/master/Dat...
I haven't finished it yet
you can see how it's done here:
phpactiverecord.org
propelorm.org
So far I've got the
AR class itself like this
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();
}
}
namespace Models;
use Core\Db\Model;
class Users extends Model
{
}
use Models\Users;
$user = new Users();
$user->email = '[email protected]';
$user->name = "User88";
$user->save();
I highly recommend reading Fowler Martin and abandoning AR
DataMapper in many ways better - you separate domain objects and the layer that drives them to the database and back
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question