Doctrine / Symfony 一对多关系中 getSomethings 的返回值是多少?

Oli*_*ria 4 php orm symfony doctrine-orm

我喜欢类型提示或从 PHP7 开始实际显示 getter 函数的返回值。但是对于 Doctrine / Symfony 中的一对多关系,我仍然陷入困境,并且不确定要添加到标签中的内容@var

\n\n
[...]\n\n/**\n * @var string\n * @ORM\\Column(name="name", type="string")\n */\nprivate $features;\n\n\n/**\n * What goes into var here?\n *\n * One Product has Many Features.\n * @ORM\\OneToMany(targetEntity="Feature", mappedBy="product")\n */\nprivate $features;\n\npublic function __construct()\n{\n    $this->features = new ArrayCollection();\n    $this->name = \'New Product Name\';\n}\n\n/**\n * @return Collection\n */\npublic function getFeatures(): Collection\n{\n    return $this->features;\n}\n\n\n[...]\n
Run Code Online (Sandbox Code Playgroud)\n\n

目前 I\xe2\x80\x99m 使用@var Collection然后可以使用 Collection 函数。但是 \xc2\xbbproper\xc2\xab 会返回什么呢?确实如此吗Collection?或者是吗ArrayCollection?我\xe2\x80\x99m 试图使用Features[]Feature 的功能,如果我需要的话(而不是打字提示),但它\xe2\x80\x99 感觉不对。

\n\n

\xc2\xbbcleanest\xc2\xab / 稳定的方法是什么?

\n

dbr*_*ann 5

如果您想保留文档块,我将使用联合类型|来指定集合及其包含的值列表,例如:

/**
 * @var Collection|Feature[]
 */
Run Code Online (Sandbox Code Playgroud)

这样,当您从集合中获取单个对象(例如在 foreach 中)时,您的 IDE 应该既可以从 Collection 中找到方法,也可以找到功能类型提示。

至于ArrayCollection与Collection的问题,通常建议为接口(本例中为Collection)键入提示。ArrayCollection 提供了更多方法,但除非您确实需要它们,否则我不会仅仅为了获取它们而费心使用类型提示。

我在项目中倾向于做的是将 Collection 保留在实体内,并仅在 getter 中传递一个数组,如下所示:

public function getFeatures(): array
{
    return $this->features->toArray();
}

public function setFeatures(array $features): void
{
    $this->features = new ArrayCollection($features);
}
Run Code Online (Sandbox Code Playgroud)

请注意,voidPHP 7.0 尚不支持返回类型。返回数组的好处是,在代码中您不必担心使用哪种 Collection Doctrine。该类主要用于维护 Doctrine 工作单元内对象之间的引用,因此它不应该成为您真正关心的部分。