Answer the question
In order to leave comments, you need to log in
Need to make changes to a class?
I had a task, I completed it. But I need to make corrections. I can't deal with them.
Changes:
"When saving data, it is necessary to take into account the keys of the new data and those data that are stored in the database (file), if the value with the key in the database (file) already exists, then you need to replace its value with a new one."
- "Classes FileBox and DbBox must be implemented in such a way that it is impossible to create more than one instance of each of the classes."
<?php
interface Box
{
public function setData($key, $value);
public function getData($key);
public function save();
public function load();
}
abstract class BoxAbstract implements Box
{
protected $data = [];
public function setData($key, $value)
{
$this->data[$key] = $value;
}
public function getData($key)
{
return $this->data[$key] ?? null;
}
public abstract function save();
public abstract function load();
}
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("INSERT 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;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question