Skip to content

Commit 1414ddd

Browse files
authored
Merge pull request #56 from aternosorg/save-registry
Add option to prevent saving models to the registry when calling ->save()
2 parents c2b6db0 + 7dac3f0 commit 1414ddd

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

‎src/GenericModel.php‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -625,15 +625,16 @@ public function reload(): static
625625
/**
626626
* Save the model changes
627627
*
628+
* @param bool $saveToRegistry save the model to the registry (if enabled)
628629
* @return bool
629630
*/
630-
public function save(): bool
631+
public function save(bool $saveToRegistry = true): bool
631632
{
632633
// new model, generate id and save in registry
633634
if (!$this->getId()) {
634635
$this->generateId();
635636

636-
if (static::$registry) {
637+
if (static::$registry && $saveToRegistry) {
637638
ModelRegistry::getInstance()->save($this);
638639
}
639640
}

‎test/tests/TestDriverTest.php‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,25 @@ public function testGetWithRegistry(): void
755755
$this->assertSame($item2, ModelRegistry::getInstance()->get(TestModel::class, $id));
756756
}
757757

758+
public function testSaveWithRegistry(): void
759+
{
760+
$item = new TestModel();
761+
$this->assertNull($item->getId());
762+
763+
$item->save(false);
764+
$this->assertNull(ModelRegistry::getInstance()->get(TestModel::class, $item->id));
765+
766+
// Models are only added to the registry when they are saved for the first time
767+
$item->save();
768+
$this->assertNull(ModelRegistry::getInstance()->get(TestModel::class, $item->id));
769+
770+
// Reset id to create a new model
771+
$item->setId(null);
772+
773+
$item->save();
774+
$this->assertSame($item, ModelRegistry::getInstance()->get(TestModel::class, $item->id));
775+
}
776+
758777
protected function tearDown(): void
759778
{
760779
TestModel::clearTestEntries();

0 commit comments

Comments
 (0)