开发者

Docblocks for Doctrine collections

Is there a standard way to document the expected class of entities inside a Collection in the docblock comment in a Doctrine project? Something like:

/**
 * @var Collection<User>
 */
protected $users;

Looks like PHPDoc is the de-开发者_JAVA百科facto standard for docblock annotations now, but I couldn't find any mention for this use case.


Here is a solution that enables you to have autocompletion both on the Collection methods and your objects methods:

/**
 * @param Collection|User[] $users
 */
public function foo($users)
{
    $users-> // autocompletion on Collection methods works

    foreach ($users as $user) {
        $user-> // autocompletion on User methods work
    }
}

It works like a charm in PhpStorm at least.


UPDATE 2022

Doctrine now documents the generic types of Collection with the @template syntax, which is nowadays supported by PhpStorm & static analysis tools (Psalm & PHPStan) at least:

/**
 * @var Collection<int, User>
 */
protected Collection $users;

The old PhpStorm hacky way of documenting this, Collection|User[] is no longer required.


There are a few different ways to document expected variables. Have a look at the phpDoc documentation for a full list of available tags.

class MyClass
{
    /**
     * Users collection
     * @var \Doctrine\ORM\ArrayCollection
     */
    protected $users;

    /**
     * My method that doesn't do much
     * @param \Doctrine\ORM\ArrayCollection $users
     * @return void
     */
    public function myMethod(\Doctrine\ORM\ArrayCollection $users)
    {
        /** @var \Entities\Users $user */
        $user = current($this->users);
    }
}


I think User[] should work. Don't remember where I found that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜