AsyncOrm/src/DbObject.php

78 lines
2.2 KiB
PHP
Raw Normal View History

2024-03-17 20:20:00 +01:00
<?php declare(strict_types=1);
/**
* This file is part of AsyncOrm.
* AsyncOrm is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* AsyncOrm is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with AsyncOrm.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
* @author Alexander Pankratov <alexander@i-c-a.su>
* @copyright 2016-2024 Daniil Gentili <daniil@daniil.it>
* @copyright 2016-2024 Alexander Pankratov <alexander@i-c-a.su>
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
* @link https://daniil.it/AsyncOrm AsyncOrm documentation
*/
namespace danog\AsyncOrm;
2024-03-26 18:32:26 +01:00
use danog\AsyncOrm\Internal\Containers\ObjectContainer;
2024-03-17 20:20:00 +01:00
2024-03-26 18:32:26 +01:00
/** @api */
2024-03-24 19:23:32 +01:00
abstract class DbObject
2024-03-17 20:20:00 +01:00
{
2024-03-26 18:32:26 +01:00
private ObjectContainer $mapper;
2024-03-28 20:32:20 +01:00
private string|int|null $key;
2024-03-25 20:13:13 +01:00
2024-03-17 20:20:00 +01:00
/**
* Initialize database instance.
2024-03-28 20:16:31 +01:00
*
* @internal Do not invoke manually.
2024-03-17 20:20:00 +01:00
*/
2024-03-28 20:16:31 +01:00
final public function initDb(ObjectContainer $mapper, string|int $key): void
2024-03-17 20:20:00 +01:00
{
2024-03-28 20:32:20 +01:00
if (isset($this->key)) {
2024-03-28 21:22:35 +01:00
$this->mapper = $mapper;
$this->key = $key;
2024-03-28 20:32:20 +01:00
return;
}
2024-03-25 20:13:13 +01:00
$this->mapper = $mapper;
$this->key = $key;
2024-03-26 18:46:59 +01:00
$this->onLoaded();
2024-03-25 20:13:13 +01:00
}
/**
* Save object to database.
*/
public function save(): void
{
2024-03-26 18:32:26 +01:00
$this->onBeforeSave();
$this->mapper->inner->set($this->key, $this);
$this->onAfterSave();
}
2024-03-26 18:46:59 +01:00
/**
* Method invoked after loading the object.
*/
protected function onLoaded(): void
{
}
2024-03-26 18:32:26 +01:00
/**
* Method invoked before saving the object.
*/
2024-03-26 18:32:45 +01:00
protected function onBeforeSave(): void
{
2024-03-26 18:32:26 +01:00
}
/**
* Method invoked after saving the object.
*/
2024-03-26 18:32:45 +01:00
protected function onAfterSave(): void
{
2024-03-17 20:20:00 +01:00
}
}