I was reading up on Doctrine 2, and I came across this post http://groups.google.com/group/doctrine-dev/browse_thread/thread/3b21fcea5a408aae, in which a user wanted to extend the PersistantCollection class with a custom collection. In it, another user responds,
Collections are collections, they hold elements and provide means to
iterate over them or do other typical collection stuff (count, filter items, add items, remove items, ...), always not caring about the exact nature of the items (products, articles or whatever). getTotalPrice or getTotalWeight on a collection are completely misplaced and extending collection classes a similar bad idea in most situations. It goes against many guidelines, single responsibility principle being one of them. Put your business logic on your domain objects/开发者_JAVA百科classes themselves, not on the collections. Collections are just generic data containers.
My question is, if I wanted to do something with a collection of book objects, like sort them into categories and count the amount within each category, would it be incorrect to create a method within the collection class to do this? Or should I make a static function within the entity to sort the collection? I'm just not really sure where I would put this type of function.... Thanks in advance for taking time out of your day to read this post. Cheers!
No, I would highly recommend against custom collections. The Collection
interface provides a full public API to manipulate the collection in anyway, eliminating the need to subclass the collection.
In your Category
you could write a method that sorts the $books
collections. ...And possibly hook it into a PostLoad event. (Why did you suggest a static
method?)
精彩评论