[DCOM-258] ArrayCollection - add method repeats objects Created: 19/Nov/14  Updated: 19/Nov/14  Resolved: 19/Nov/14

Status: Resolved
Project: Doctrine Common
Component/s: Collections
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Pablo Santiago Sánchez Assignee: Marco Pivetta
Resolution: Won't Fix Votes: 0
Labels: collection

Any OS - PHP 5.x.x


The add method allows an already included object to be included n number of times. This means that the same object maybe processed more times than needed, and also index does not match object count. If you have 3 objects and the same object is repeated 3 times, developers need to create another control array to guarantee that no object is processed twice.

The code bellow fix the problem on ArrayCollection class:

     * {@inheritDoc}
    public function add($value)
    	if (is_object($value)) {
	    	if (is_array($this->_elements)) {
	    		if (in_array($value, $this->_elements)) {
	    			return true;
        $this->_elements[] = $value;
        return true;

Comment by Marco Pivetta [ 19/Nov/14 ]

This is intended API behavior.

Comment by Pablo Santiago Sánchez [ 19/Nov/14 ]

How can reprocessing be the expected behauviour? It lowers performance and also creates unnecessary risk to applications.

Comment by Marco Pivetta [ 19/Nov/14 ]

What you are looking for is for a Set, not a Collection

Comment by Pablo Santiago Sánchez [ 19/Nov/14 ]

Ok, so, where's doctrine set class? I couldn't find any.

Comment by Marco Pivetta [ 19/Nov/14 ]

Doctrine does not provide such a functionality. I suggest looking at projects such as https://github.com/morrisonlevi/Ardent and https://github.com/morrisonlevi/SPL-Collections instead

Comment by Pablo Santiago Sánchez [ 19/Nov/14 ]

Already implemented, don't worry. If you think this is a desired behaviour, ok.

I extended the ArrayCollection and changed a bit the behaviour to make a Set with no repeated objects in it. Since objects are passed as references, I have no need to overprocess anything and need better performance. Perhaps, someday, when I need this behaviour I go back to the original ArrayCollection.

Thank you.

Comment by Marco Pivetta [ 19/Nov/14 ]

Pablo Santiago Sánchez be aware that you cannot avoid this behavior when using a Doctrine\ORM\PersistentCollection (when in ORM context)

Generated at Wed Nov 26 08:05:32 UTC 2014 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.