I'm trying to do some experiments with arrays and objects to improve my PHP programming basics.
What I would like to do is to save a collection of objects instantiated by one of my classes in a text file to be able to fetch them later.
My current implementation is to save the objects in an array, encode the array and save it to a JSON file.
However, the problem that arises is that when I then go to extract the objects these are no longer objects deriving from my class but are transformed into stdClass objects.
Here is the method I use to save objects to the file:
public function store(string $titolo, string $nomeAutore, string $titoloToDoList): void
{
FileChecker::FindOrBuild('Data/Tasks.json', "[]");
$newTask = new Task($titolo, $nomeAutore, $titoloToDoList);
$file = file_get_contents('Data/Tasks.json');
$decodedFile = json_decode($file);
array_push($decodedFile, $newTask->toArray());
file_put_contents('Data/Tasks.json', json_encode($decodedFile));
FileChecker::FindOrBuild('log/log.txt', "Logs: \n");
Logger::logTaskStore($nomeAutore, $titoloToDoList);
}
and then I extract from the file with a simple json_decode ()
Can anyone suggest some alternative method to save objects in a text file without losing the class?
edit:
forgot to put the toArray()
code which is simply
public function toArray(): array
{
return get_object_vars($this);
}
My Answer:
'[]');
$tasks = json_decode(file_get_contents('Data/Tasks.json'));
$task = new Task($titolo, $nomeAutore, $titoloToDoList);
$tasks[] = $task;
file_put_contents('Data/Tasks.json', json_encode($tasks));
}
And here is the method I use to fetch the objects from the file:
public function fetch(): array
{
$tasks = json_decode(file_get_contents('Data/Tasks.json'));
$result = [];
foreach ($tasks as $task) {
$result[] = (object) $task;
}
return $result;
}
As you can see, in the fetch method, I am casting each task object to a stdClass object, which is not what I want.
Is there a way to fetch the objects from the file without losing their original class?
Rate this post
5 of 5 based on 3731 votesComments