Matheus Oliveira Matheus Oliveira - 1 year ago 62
PHP Question

How to create one property based in another property of the same document?

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?

Answer Source

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();


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download