The issue is to save an object and retrieve it back the way it was before saving. Currently serializing the object -> saving the serialized as a file -> unserializing the file
works. But what if I want to save the object in database? (While in mind that storing a serialized object in a database is not a good practice, since my object can get really big)
In this case, I have a data-access-layer which takes the object's properties and maps them to a table's fields. The question is how to read the data back into the same object as it was before saving? Something like what unserialize()
does would fit the issue: it creates an object from the given data without hitting the constructor or anything else.
Let's say this is the class I want to store in the DB:
class MyClass {
private $property;
public function __construct(string $required_data) {
if(empty($required_data)) throw new Exception("Cannot be empty");
}
public function load($arr) {
foreach($arr as $key => $value) {
$this->$key = $value;
}
}
}
Obviously that load()
method up there, and something like the code below won't work in this case:
$obj = new MyClass(); // Throws an exception
$obj->load(['property' => 'value']);