Custom Collections through delegation
Author: beberleiCreated Oct 9, 2024Updated Jul 26, 2026
Users regularly want to introduce their own collections. We don't want to expose the Collection interface due to its complexity there is too much risk. MongoDB ODM has a code generated solution for this, for ORM I propose we do this with delegation.
- doctrine/collections introduces a
DelegateCollectionwith all methods implemented as final, delegating to $delegatee, and one custom methodgetInternalDelgatee. - In ORM association configuration, allow optional "collectionType" information. When present, ORM converts with logic:
- create collection
new $assoc['collectionType](new PersistentCollection(...))everywhere a PersistentCollection is created. - introspect collection
$col = $col instanceof DelegateeCollection ? $col->getDelegatee() : $col
- create collection
- Improve AttributeDriver to detect that a collection type instanceof DelegateeCollection and set
collectionTypekey automatically. - Precondition: In ORM, if collection types are configured and Composer\PackageVersions for doctrine/collection is not high enough, throw.
Example code:
class CommentCollection extends DelegateCollection
{
public function getEnabled() {
return $this->delegatee->filter(fn ($comment) => $comment->isEnabled);
}
}
class Post
{
private CommentCollection $comments;
public function getComments(): CommentCollection
{
return $this->comments;
}
}Reference:
Source: doctrine/orm