php - 如何在 Symfony 4 中使用自定义集合

标签 php symfony doctrine-orm doctrine symfony4

我想为我的 Symfony 4 应用程序使用自定义集合类。以下场景是我想要实现的一个示例:

我有一个帖子收集类,它有一些用于过滤和映射数据的实用程序。

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;
        });
    }
}

也是用户类,它是一个 Doctrine 实体。

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;
    }
}

然后在帮助器或 Controller 中有一个方法将访问用户的数据,如下所示:

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

    // Render the titles...
}

上述方法在手动创建新对象时有效,例如在单元测试中。但是从存储库加载实体时它不起作用,因为这样集合将被 Doctrine\ORM\PersistentCollection 对象填充。

我现在的问题是,如何配置我的应用,以便在加载实体时使用自定义持久性集合(例如 PersistentPostCollection)?

我确实找到了这个页面 https://www.doctrine-project.org/projects/doctrine-collections/en/latest/lazy-collections.html#lazy-collections ,但我找不到如何将其集成到 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.

最佳答案

你找到的是 Doctrine Collections 包的文档。

Doctrine ORM 使用 Doctrine Collections 包,但它们是相互独立的包。因此,您可以创建自定义集合这一事实并不意味着 ORM 会尊重这一点。

Doctrine ORM 现在无法实现您想要做的事情。

feature of custom collections预定next major Doctrine ORM version .

关于php - 如何在 Symfony 4 中使用自定义集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54867001/

相关文章:

php - 未知列类型 "json"请求运行 Doctrine 2 迁移

PHP MySQL 连接没有套接字文件

php - MYSQL 行没有正确递增

php - Symfony 2 - 多种形式

error-handling - Symfony形式虚拟错误

php - 将可嵌入字段设置为父实体映射的主键 - Doctrine2

php - 如何使用公共(public)字段连接mysql中的两个表

javascript - 如何使用 Javascript 和 PHP 启用鼠标滚轮水平滚动

forms - 通过实体的所有属性搜索关键字,Symfony2

php - 从其他表 + Doctrine 查询