Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.



7.1k
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.phalconphp.com/en/latest/reference/models.html#initializing-preparing-fetched-records