Added sort option for array collection #213

Closed
wants to merge 2 commits into
from

Projects

None yet

5 participants

@andrewtarry

I have added a sorter class and sortBy method for the ArrayCollection class. It gives the option to reorder the ArrayCollection after someone has gotten it from the database, e.g. from a relationship. It takes an array of method names to sort by in order to priority and it takes an optional boolean to set the order to ascending. Here is an example:

$arraycollection->sortBy(array('getName()', 'getAddress()'));

It will recursively loop the collection change the order. Each time it will look to see if the previous matching option is the same as for the previous element and then store those elements in list to be reordered.

Once it has looped all the elements it will reorder the elements it has matched and if there is another option to reorder by it will loop only the elements it matched last time so it is not looping the whole array each time.

@doctrinebot

Hello,

thank you for positing this Pull Request. I have automatically opened an issue on our Jira Bug Tracker for you with the details of this Pull-Request. See the Link:

http://doctrine-project.org/jira/browse/DCOM-134

@Ocramius
Member

@andrewtarry are you sure this wouldn't work by re-using the matching API internally?

@stof stof commented on the diff Nov 21, 2012
.gitignore
@@ -2,3 +2,5 @@ build/
logs/
reports/
dist/
+/nbproject/private/
+/nbproject
@stof
stof Nov 21, 2012 Member

Please remove this. Files specific to your IDE should be ignored locally. See https://help.github.com/articles/ignoring-files for help

@stof stof commented on the diff Nov 21, 2012
lib/Doctrine/Common/Collections/ArrayCollection.php
@@ -496,5 +496,17 @@ public function matching(Criteria $criteria)
return new static($filtered);
}
+
+ /**
+ * Reorder the elements by a series of methods to reorganise the elements.
+ *
+ * @param array $sortBy An array of method names to regoraise by.
+ * @param boolean $ascend [Optional] True if the order should be ascending
+ */
+ public function sort(array $sortBy, $ascend = false)
@stof
stof Nov 21, 2012 Member

Adding the method in the class without adding it in the interface is useless (you cannot ensure you will receive an ArrayCollection each time). And adding it in the interface is impossible as it would be a BC break

@beberlei
Member

This cannot work, as everything on ArrayCollection has to be on the Collections interface and extending that is not possible because of BC. Also the automatic sorting is way to performance intensive.

You should build yourself a helper object that allows sorting of collections, we cannot add this sort of code, sorry :-(

@beberlei beberlei closed this Jan 10, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment