refactor(model): Track model persistence state

This commit is contained in:
2026-03-11 18:48:32 -03:00
parent 76a69e5ef8
commit 3770dd6d9b

View File

@@ -43,6 +43,10 @@ class Model
*/ */
protected static array $dbForceSave = []; protected static array $dbForceSave = [];
/**
* @var bool Attribute that persis if is current model is saved into the database
*/
protected bool $dbIsSaved = false;
/** /**
* @var string The database table name. * @var string The database table name.
@@ -306,6 +310,8 @@ class Model
} }
} }
$instance->markAsSaved();
return $instance; return $instance;
} }
@@ -466,23 +472,34 @@ class Model
$pk = static::$dbPrimaryKey; $pk = static::$dbPrimaryKey;
$this->$pk = $db->lastInsertId(); $this->$pk = $db->lastInsertId();
$this->markAsSaved();
} }
/** /**
* Checks if the object to be saved is new or not, and based on the result, * Checks if the object to be saved is new or not, and based on the result,
* calls `update` to update an existing row or `add` to insert a new row. * calls `update` to update an existing row or `add` to insert a new row.
*
* @return void * @return void
*/ */
public function save(): void public function save(): void
{ {
$pk = static::$dbPrimaryKey; if ($this->dbIsSaved) {
if (isset($this->$pk)) {
$this->update(); $this->update();
} else { } else {
$this->add(); $this->add();
} }
} }
/**
* Mark the current instance as already saved
*
* @return void
*/
public function markAsSaved(): void
{
$this->dbIsSaved = true;
}
/** /**
* Deletes the current object from the database. * Deletes the current object from the database.
* @return void * @return void
@@ -495,6 +512,7 @@ class Model
static::$dbQueryVariables[":$pk"] = $this->$pk; static::$dbQueryVariables[":$pk"] = $this->$pk;
static::query($sql); static::query($sql);
$this->dbIsSaved = false;
} }
/** /**