Skip to content

Result Hydration

Glynn Quelch edited this page Jan 25, 2022 · 16 revisions

Setting Model Values

When we come to set values, there is a small flow the Hydrator follows.

  • First it will check if PSR12 setter exists setColumnName this will add set to the start of the property name and capitalise the first char myVal would become setMyVal()
  • Second we check if an underscored setter exists, this adds set_ to the start of the property myVal would become set_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.

Model Example

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)
Clone this wiki locally