Как применить паттерн Singltone к классу?
Мне нужно применить паттерн Singltone к двум классом (FileBox и DbBox), но т.к. я только учусь, не могу справится с этой задачей.
class FileBox extends BoxAbstract
{
private $file;
public function __construct($file)
{
$this->file = $file;
}
public function save()
{
file_put_contents($this->file, serialize($this->data));
}
public function load()
{
$this->data = unserialize(file_get_contents($this->file));
}
}
class DbBox extends BoxAbstract
{
private $pdo;
public function __construct(\PDO $pdo)
{
$this->pdo = $pdo;
}
public function save()
{
$this->pdo->beginTransaction();
$this->pdo->query('DELETE FROM box')->execute();
$stmt = $this->pdo->prepare("UPDATE INTO box (key, value) VALUES (:key, :value)");
foreach ($this->data as $key => $value) {
$stmt->bindValue(':key', $key);
$stmt->bindValue(':value', serialize($value));
$stmt->execute();
}
$this->pdo->commit();
}
public function load()
{
$stmt = $this->pdo->query('SELECT key, value FROM box_items');
$data = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$data[$row['key']] = unserialize($row['value']);
}
$this->data = $data;
}
Вот что получилось:
class FileBox extends BoxAbstract
{
private $file;
private static $_instance;
private function __construct($file)
{
$this->file = $file;
}
public static function init(): FileBox
{
if(self::$_instance === null){
self::$_instance = new self();
}
return self::$_instance;
}
public function save()
{
file_put_contents($this->file, serialize($this->data));
}
public function load()
{
$this->data = unserialize(file_get_contents($this->file));
}
}
class DbBox extends BoxAbstract
{
private $pdo;
private static $_instance;
private function __construct(\PDO $pdo)
{
$this->pdo = $pdo;
}
public static function init(): DbBox
{
if(self::$_instance === null){
self::$_instance = new self();
}
return self::$_instance;
}
public function save()
{
$this->pdo->beginTransaction();
$this->pdo->query('DELETE FROM box')->execute();
$stmt = $this->pdo->prepare("UPDATE INTO box (key, value) VALUES (:key, :value)");
foreach ($this->data as $key => $value) {
$stmt->bindValue(':key', $key);
$stmt->bindValue(':value', serialize($value));
$stmt->execute();
}
$this->pdo->commit();
}
public function load()
{
$stmt = $this->pdo->query('SELECT key, value FROM box_items');
$data = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$data[$row['key']] = unserialize($row['value']);
}
$this->data = $data;
}