doctrine/mongodb — Issue #30: Collections, References and EventManager
Author: dragoonis
Created: 2011-11-09 17:03:23+00:00
State: open

Here's something that I stumbled upon while integrating this lib into PPI and I feel it's necessary to discuss something.

A lot of PHP power users will be doing anonymous arrays like so:

``` php
insert(array(
'username' => 'paul'
));
```

I received the error:
Fatal error: Cannot pass parameter 1 by reference in /Applications/XAMPP/xamppfiles/htdocs/ppi-demo/App/Controller/Demo.php on line 31

I immediately knew what was wrong, because I read most of the source code of this library prior to using it. However for the number of users that are using this library out-right there is a possible pitfall that users may/will fall into and could throw them off.

https://github.com/doctrine/mongodb/blob/master/lib/Doctrine/MongoDB/Collection.php#L494
This function's declaration is:

``` php
public function insert(array &$a, array $options = array())
```

Of course this by-ref $a is so that it can be manipulated via the event listeners and such. However, since we can't check if the user passed an anonymous array or not as it produces a fatal error.

If you look at the function body, the reference is kept here so that it can go down into the event manager and back out again. What if we just make a local copy and then pass that to the event manager ?

My proposal here, to allow users to avoid this pitfall and pass anonymous arrays into insert() is the following which is a +2 in my opinion.

``` php
eventManager->hasListeners(Events::preInsert)) {
$this->eventManager->dispatchEvent(Events::preInsert, new EventArgs($this, $b));
}

$result = $this->doInsert($b, $options);

if ($this->eventManager->hasListeners(Events::postInsert)) {
$this->eventManager->dispatchEvent(Events::postInsert, new EventArgs($this, $result));
}
return $result;
}
```

Thoughts?

Thanks for your time.
- Paul.