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

问题描述:

我喜欢在PHP7中使用类型提示或开始实际显示getter函数的返回值。但是在Doctrine/Symfony中的一对多关系中,我仍然陷入困境,不确定要添加到@var标记中。在Doctrine/Symfony一对多关系中,getSomethings的返回值是多少?

[...] 

/** 
* @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?或者是ArrayCollection?我很想用Features[]为了使用功能的功能,如果我需要(而不是typehinting),但它感觉不对。

什么是“最干净”/稳定的方式来做到这一点?

如果你想保持我会使用union类型|双方指定集合和值包含像列表中的docblock:

/** 
* @var Collection|Feature[] 
*/ 

有了这个您的IDE都应该找到收集方法以及从集合中获取单个对象时的Feature-type提示,例如在一个foreach。

至于ArrayCollection与Collection的问题,通常建议为接口输入提示(在这种情况下为Collection)。 ArrayCollection提供了一些更多的方法,但除非你真的需要它们,否则我不会为了得到它们而使用类型提示。

我倾向于在项目中做的是保持集合的实体内部,并且仅通过了在吸气像这样的数组:

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

public function setFeatures(array $features): void 
{ 
    $this->features = new ArrayCollection($features); 
} 

要小心,void返回类型不是在PHP 7.0支持然而。返回一个数组的好处是在你的代码中你不必担心什么样的Collection Doctrine使用。该类主要用于维护原则的工作单元内的对象之间的引用,所以它不应该成为您关心的一部分。

+0

感谢您的建议! ' - > toArray()'方式听起来相当不错(因为ArrayCollection大部分都是'array'的封装),我会放弃它;我将更改我的IDE中的getter模板,并且应该可以工作。 'Collection | Feature []'的方式听起来很实用,但我觉得它有点不干净。我主要使用AWS ElasticBeanstalk,几周前他们开始支持PHP 7.1,所以void返回类型现在也应该是好的! –