Answer the question
In order to leave comments, you need to log in
A class for working with a specific table?
I'm writing a class to work with a specific table, but it seems to me that I'm somehow writing it incorrectly or something, redneck code) Are there examples of how to write such a class correctly? For example, I can't imagine how to get multiple records + add a save
. For example, so that when passing through the loop, I can tweak the value and call save
.
How the code looks now:
class Account {
private $database;
private $properties = [];
private $updated = [];
public function __construct($database) {
$this->database = $database;
}
public function __get($name) {
if(isset($this->properties[$name])) {
return $this->properties[$name];
}
}
public function __set($name, $message) {
if(isset($this->properties[$name])) {
if((string) $name != 'id') {
$this->updated[$name] = $message;
$this->properties[$name] = $message;
}
}
}
public function getById($id) {
$object = $this->database->query('SELECT * FROM `ACCOUNTS` WHERE `id` = ?', [ $id ])->fetch();
if(isset($object->id)) {
$this->properties = json_decode(json_encode($object), true);
}
}
public function save() {
if(isset($this->properties['id'])) {
if(!empty($this->updated)) {
$prepare = 'UPDATE `ACCOUNTS` SET ';
$prepare .= '`' . implode('` = ?, `', array_keys($this->updated)) . '` = ? ';
$prepare .= 'WHERE `id` = ?';
$this->updated += [ 'id' => $this->properties['id'] ];
$this->database->query($prepare, array_values($this->updated));
$this->updated = [];
}
}
}
}
$account = new Account($database);
$account->getById(1);
$account->username = '@tests';
$account->save();
Answer the question
In order to leave comments, you need to log in
What you are trying to implement is the ActiveRecord pattern, google the implementations.
And the nuances
Instead
public function getById($id) {
$object = $this->database->query('SELECT * FROM `ACCOUNTS` WHERE `id` = ?', [ $id ])->fetch();
if(isset($object->id)) {
$this->properties = json_decode(json_encode($object), true);
}
}
public function getById($id) {
$object = $this->database->query('SELECT * FROM ? WHERE `id` = ?', [ $this->table, $id ])->fetch();
if(isset($object->id)) {
$this->properties = json_decode(json_encode($object), true);
}
}
if(isset($object->id)) {
$this->properties = json_decode(json_encode($object), true);
}
I can’t imagine how to get multiple records + add the save method to each of these recordsfindCollectionById method, for example. Returns an array of objects to you. You loop through this array and call save() for each object.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question