[英]What is the return value of getSomethings in a Doctrine / Symfony One-To-Many Relationship?
我喜欢使用类型提示或在 PHP7 中开始实际显示 getter 函数的返回值。 但是在 Doctrine / Symfony 中的一对多关系中,我仍然被困住并且不确定要添加到@var
标签中的内容。
[...]
/**
* @var string
* @ORM\Column(name="name", type="string")
*/
private $features;
/**
* What goes into var here?
*
* One Product has Many Features.
* @ORM\OneToMany(targetEntity="Feature", mappedBy="product")
*/
private $features;
public function __construct()
{
$this->features = new ArrayCollection();
$this->name = 'New Product Name';
}
/**
* @return Collection
*/
public function getFeatures(): Collection
{
return $this->features;
}
[...]
目前我正在使用@var Collection
,然后可以使用Collection 函数。 但是返回什么是“正确”的东西? 真的是Collection
吗? 或者它是ArrayCollection
? 如果需要(而不是打字提示),我很想使用Features[]
来使用 Feature 的功能,但感觉不对。
什么是“最干净”/稳定的方法来做到这一点?
如果你想保留文档块,我会使用联合类型|
指定集合及其包含的值列表,例如:
/**
* @var Collection|Feature[]
*/
有了这个,当您从集合中获取单个对象(例如在 foreach 中)时,您的 IDE 应该同时从集合中找到方法以及功能类型提示。
关于ArrayCollection vs.Collection的问题,通常建议接口(这里是Collection)输入hint。 ArrayCollection 提供了更多的方法,但除非你真的需要它们,否则我不会为了获得它们而费心使用类型提示。
我在项目中倾向于做的是将 Collection 保留在实体中,并且只像这样在 getter 中传递一个数组:
public function getFeatures(): array
{
return $this->features->toArray();
}
public function setFeatures(array $features): void
{
$this->features = new ArrayCollection($features);
}
请注意,PHP 7.0 尚不支持void
返回类型。 返回数组的好处是在您的代码中您不必担心使用哪种 Collection Doctrine。 该类主要用于维护 Doctrine 的工作单元内的对象之间的引用,因此它不应该真正成为您关注的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.