Alexandre
Alexandre

Reputation: 3170

Storing serialized object with doctrine

I got some problem with storing php serialized object with doctrine, when I use the following code to store:

$item = new \Company\MyBundle\Entity\Frontend\table();
$item->setData(serialize($myPhpObject));
$this->_em->persist($item);
$this->_em->flush();

Then in another instance:

$item = $this->_em->getRepository('MyBundle:frontend\table')->findOneById(...);
echo $item->getData(); // display only a part of the serialized object

I found somehow a fix but I guess there is something better to do:

$item->setData(json_encode(serialize($myPhpObject)));

When I use this the all serialized string is stored and I can unserialize it correctly. Do you have any idea about what is wrong?

-edit-

this would be an example of setting from the column data:

data:
    type: string
    length: null
    fixed: false
    nullable: true
    column: data

Upvotes: 2

Views: 9870

Answers (2)

WebHQ
WebHQ

Reputation: 711

I assume that you are using annotations as your doctrine configuration. Then in your entity you can use the object type:

// src/Company/MyBundle/Entity/Frontend/table.php
// ...
/**
 * @var resource
 *
 * (non-PHPdoc)
 * @ORM\Column(name="data", type="object")
 */
private $data;
// ...

Then inside your controller it is not necessary to serialize / unserialize object, doctrine will handle that:

// src/Company/MyBundle/Controller/SomeController.php
// ...
// write
$item = new \Company\MyBundle\Entity\Frontend\table();
$item->setData($myPhpObject);

$this->_em->persist($item);
$this->_em->flush();

// ...
// read
$item = $this->getDoctrine()->getRepository('CompanyMyBundle:table')->find($id);
$myPhpObject = $item->getData();
var_dump($myPhpObject);
// ...

Good Luck!

Upvotes: 4

Momchil Milev
Momchil Milev

Reputation: 25

Using ArrayType (a.k.a. array in Entity Annotation) or ObjectType (a.k.a. object in Entity Annotation) for Doctrine type might have some potential security issues (causing a Denial of service) because of this issue (https://github.com/doctrine/dbal/issues/3289)

I, myself, would use JsonObjectType instead.

Upvotes: 0

Related Questions