There are times when form data must be serialized before being saved in a database. An example would be saving multiple parameters within an array, then serializing the array, which converts the array into one long string.

Working within Symfony the best place to add the serialize() method is as close to the data as possible, so any calling code will be forced to work the same way, serialize upon create/update, unserialize upon retrieve. To do this you will need to overload the setters in the object class file.

Before

class Object extends BaseObject
{
}

After

class Object extends BaseObject
{
    public function setData($data)
    {
        serialize($data);
        parent::setData($data);
    }

    public function getData()
    {
        return unserialize($this->data);
    }
}

As you can see, in the ‘after’ example, we have overloaded the setData() and getData() methods in the BaseObject class with our own custom methods, which serialize/unserialize the data. We call on the BaseObject::setData() b/c there is some extra data handling that is conducted and we want to maintain that behavior.

One last thing, if you submitted data via a form,  you will need to give the serialized data candidate a special validator:

Before

class BaseForm
{
     $this->setValidators(array(
         'formElement' => new sfValidatorString()
     );
}

class Form extends BaseForm
{
}

After

class BaseForm
{
    $this->setValidators(array(
        'formElement' => new sfValidatorString()
    );
}

class Form extends BaseForm
{
    public function configure()
    {
        $this->validatorSchema['formElement'] = new sfValidatorPass();
    }
}

Without making this change, your ‘formElement’ will be typecast as a string and you will see the word ‘Array’ in your database upon viewing saved records.