We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Auto serialize array field in class extending \Phalcon\Mvc\Model

Can I auto-serialize model fields with array type values before saving and auto-deserialize before fetching?


class MyModel extends \Phalcon\Mvc\Model 
{
    public $x;
}

$my = new MyModel;
$my->x = ['abc'];
$my->save(); 

//...

$my = MyModel::findFirst(1);
var_export($my->x); // array ('abc') 

Of course, I can use serializing logic in setters and deserializing one in getters or do it in controller but this is not what I want. I use MySQL as DB.



9.3k
Accepted
answer
edited Mar '16

Yes you can make your own model extended from \Phalcon\Mvc\Model which will implement classes afterFetch and beforeSave

class MyModel extends \Phalcon\Mvc\Model
{
    public function beforeSave()
    {
        $this->x = serialize($this->x);
    }

    public function afterFetch()
    {
        $this->x = unserialize($this->x);
    }
}

see doc here https://docs.phalcon.io/en/latest/reference/models.html#initializing-preparing-fetched-records