-
Notifications
You must be signed in to change notification settings - Fork 0
Result Hydration
Glynn Quelch edited this page Jan 25, 2022
·
16 revisions
When we come to set values, there is a small flow the Hydrator
follows.
- First it will check if
PSR12
setter existssetColumnName
this will addset
to the start of the property name and capitalise the first charmyVal
would becomesetMyVal()
- Second we check if an underscored setter exists, this adds
set_
to the start of the propertymyVal
would becomeset_myVal()
- Finally we just set as a public property, if it doesnt exist it will be added as a dynamic property (which should be avoided)
- You can handle all possibilities with the magic
__set()
method.
class FooModel {
protected int $id;
public string $someValue;
protected string $someJson;
public function setId($id): void {
// This just gives a little protected from being called again
// faux readonly
if(null !== $this->id){
throw new Exception("The id can not be reset");
}
$this->id = $id;
}
public function set_someJson($someJson): void {
// This just gives a little protected from being called again
// faux readonly
if(null !== $this->someJson){
throw new Exception("The JSON can not be reset");
}
$this->someJson = json_decode($someJson);
}
}
If we get the following data from a query
{"id":12, "someValue":"foo", "someJson":{"key":"some value"}}
When this is populated to the model, the following will happen.
- FooModel object is created
- id will be set using
$modelInstance->setId($row->id)
- someValue will be set using
$modelInstance->someValue = $row->someValue
- someJson will be set using
$modelInstance->set_someJson($row->someJson)