[Solved] Mutator not working

I have an integer duration field where I’m storing elapsed times in integer seconds.

For instance:

  • 23 means 23 seconds
  • 62 means 1 minute and 2 seconds
  • 3600 means exactly one hour

I want to show the formatted elapsed time every time I’m showing this field, so I did this accesor:

    protected function _getDuration($duration)
    {
        return isset($duration) ? (new FrozenTime($duration))->format('G:i:s') : '';
    }

…and it works well with already saved data in the database.

So, then I did a mutator:

    protected function _setDuration($duration)
    {
        return $duration;
    }

I don’t want to convert the duration field when saving, because it already comes from a beforeSave method on the table, which returns the value exactly as it should be saved:

    public function beforeSave(Event $event, Session $session)
    {
        $begin = $session->begin;
        $end = $session->end;
        
        // Only if session ended
        if (isset($end)) {
            $session->set('duration', $this->getInterval($begin, $end));
        }
    }

From what I understand reading https://book.cakephp.org/3.0/en/orm/entities.html#accessors-mutators, everything should work well. But the actual result is that the integer value saved is the rounded number of hours (not seconds!).

For instance:

  • 30 seconds is saved as 0
  • 59 minutes and 59 secons is saved as 0
  • 1 hour is saved as 1
  • 4 hours and 59 minutes is saved as 4

Apparently, Cake is using the accessor when saving the data, along with the mutator. If this is the case, WHY?

I expect Cake to use the accessor when reading the field and the mutator when saving it. That’s all.

Any idea? Thanks.

For saving in and out of the database you probably want to use complex types.

https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-complex-types

Actually, the saved data is just an integer.

Finally, I did it with a virtual property after getting info on https://github.com/cakephp/cakephp/issues/10993

Thanks, anyhow.