I'm importing data from file to many tables in database. It may look like this:
First Name, Last Name, Meeting
John, Doe, 2020-04-24 08:00:00
Some fields like "First Name" and "Last Name" are being saved in one table and other fields like "Meeting" are being saved in different tables. There are a lot of more fields and a lot of more rows in my case.
I create handler for each table and put it in a handler chain to reduce amount of code. Each handler knows which fields it can handle. My base handler class looks like this:
abstract class TableHandler
{
protected $nextHandler;
abstract public function isFieldSupported(string $field): bool;
abstract public function handle(string $fieldName, string $fieldValue);
public function next(TableHandler $nextHandler): TableHandler
{
$this->nextHandler = $nextHandler;
}
public function handleField(string $fieldName, string $fieldValue)
{
$this->handle($fieldName, $fieldValue);
if ($this->nextHandler()) {
$this->nextHandler->handleField($fieldName, $fieldValue);
}
}
public function reset(): void
{
$this->resetHandler();
if ($this->nextHandler()) {
$this->nextHandler->reset();
}
}
private function nextHandler(): bool
{
return $this->nextHandler !== null;
}
}
I use my handler chain this way:
$table1->next($table2)
->next($table3);
foreach ($data as $row) {
foreach ($headers as $index => $header) {
$table1->handleField($header, $row[$index]);
}
$id = $table1->save();
$table2->save($id);
$table3->save($id);
$table1->reset();
}
As you can see I was able to handle fields and reset all handlers by using only first handler. Chain does the rest of the job. The problem is that I don't know how can I improve saving data. When I insert record in first table I get its ID. I need to pass this ID to further handlers because rows that I insert in those tables are related to row from first table so ID is needed. Bacause of it I need to save data separately. I would like to avoid it. Is it possible?