0

I have a simple document that has its ID:

 /**
     * @MongoDB\Id(strategy="increment")
     * @Serializer\Since("2.0")
     */
    protected $id;

and a property code

/**
 * @var string
 *
 */
protected $code;

I want that the code be generated based in the ID. So I am planning to define it in the constructor

  public function __construct()
{
$this->code = (string)$this->id.(string)rand(0,1000);
}

My question is, as both are defined in the same php class, there would be any risk to define one based in another?

Any risk of the code ask for the id before it was defined? Or there is any better way of doing such thing?

Matheus Oliveira
  • 587
  • 3
  • 10
  • 33
  • is it correct that you dont want to save the code property in database and have it only for serialized object ? – john Smith Nov 28 '16 at 14:16

2 Answers2

0

Your ID will be null when you create the object. To create code property you should set it after the persist. Something like this:

 $dm = $this->get('doctrine.odm.mongodb.document_manager');

 $item = new Item();
 $item->setSomeValue($someValue);
 $dm->persist($item);
 $dm->flush();

 $item->setCode($item->getId());
 $dm->persist($item);
 $dm->flush();

As you can imagine, this is not a good practice and you should avoid it. Generate values from database ID it is not a good idea too. I recommend you to use functions like uniqid to do the workaround. Uniqid is safer, faster and cleaner.

  • 1
    While I agree it's better to generate your own ids, I would not recommend using uniqid() for it. A better option would be UUID, which can easily be generated by libraries like ramsey/uuid. – Gerry Nov 28 '16 at 13:19
  • I used the function gen_uuid() described in this related question http://stackoverflow.com/questions/307486/short-unique-id-in-php/307773 – Matheus Oliveira Nov 28 '16 at 14:19
0

if you just want the serialized obj to be like:

{
 id:123,
 code:123
}

u can just add a getter function and it will be included in serialized result

/**
 * @var string
 *
 */
protected $code;

public function getCode(){
   return $this->getId();
}

if this does not work automagicaly (should) you can use annotations for serializer:

/**
 * @JMS\Expose
 * @JMS\Accessor(getter="getCode") 
 */
private $code;

if you want to persist the code property you can do it like Vangoso, but it does not realy make sense storing the same information twice

john Smith
  • 17,409
  • 11
  • 76
  • 117