1

i'm trying to implement this pattern http://cookbook.mongodb.org/patterns/random-attribute/ in doctrine odm.

i would like to set this attribute on the pre-persist lifecycle event. To achieve the best results, i would like to use a native javascript function Math.random() because php cannot generate random floats and i would like to avoid writing a custom function for that.

is there a way to achieve this?

i tried:

    /** @PrePersist */
    public function generateRandom()
    {
        $this->random = new \MongoCode('Math.random()');
    }

but it always sets the attribute to 1, no matter the code of the function

bazo
  • 745
  • 9
  • 26

1 Answers1

-1

I'm not sure that it's best solution but, it works for me:

/**
 * @MongoDB\PrePersist()
 * @MongoDB\PreUpdate()
 */
public function generateRandom() {
    $this->random = rand();
}
Stri FInder
  • 41
  • 1
  • 4