How to use a custom collection in Symfony 4

I want to use a custom collection class for my Symfony 4 application. The following scenario is an example of what I am trying to achieve:

I have a post collection class which has some utility for filtering and mapping data.

class PostArrayCollection extends ArrayCollection implements PostCollectionInterface
{
    public function mapTitles()
    {
        return $this->map(function (Post $post) {
            return $post->getTitle();
        });
    }
public function filterPublishedAfterDate(DateTime $from)
{
    return $this->filter(function (Post $post) use ($from) {
        return $post->publishedDate() > $from;
    });
}

}

Also the user class which is a Doctrine Entity.

class User
{
/**
* @ORM\OneToMany(targetEntity=“App\Entity\Post”, mappedBy=“post”, cascade={“persist”})
*/
private $posts;

public function __construct()
{
    $this->posts = new PostArrayCollection();
}

public function getPosts(): PostCollectionInterface
{
    return $this->posts;
}

}

Then there is a method in a helper or controller which will access the user’s data like the following:

public function showPublishedPostTitlesForUser(User $user)
{
$publishedPostTitles = $user->getPosts()
->filterPublishedAfterDate(new DateTime())
->mapTitles();

// Render the titles...

}

The above works when creating a new object by hand, for example in a unit test. But it will not work when loading the entity from the repository, because then the collections will be filled with Doctrine\ORM\PersistentCollection objects.

My question now is, how do I configure my app so I can use a custom persistent collection (for example PersistentPostCollection) when loading entities?

I did find this page https://www.doctrine-project.org/projects/doctrine-collections/en/latest/lazy-collections.html#lazy-collections, but I cannot find how to integrate this into Symfony 4.

Note: The above scenario is a simple example for the sake of keeping this question short and simple to get into. I am aware that this whole problem can be avoided when using a repository to get the correct data. But that is not what I am looking for here. This question is about understanding what is possible with Doctrine collections in Symfony 4.


#php #symfony

2 Likes13.25 GEEK