簡體   English   中英

Doctrine / Symfony 一對多關系中 getSomethings 的返回值是什么?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM