Using DocBlocks with Generics for Custom Collections
Hello,
I have a custom collection for a model, like a UserCollection with special abilities. Laravel uses the standard @template tag to make the IDE and Code Analysers aware of the generic ability of the Collection class.
My UserCollection extends the Collection class. How can I use the docblocks to tell PHPStorm, that the TValue inside the Collection is always a User model? I found the following resources, but I don't quite understand what I have to do to achieve this:
To specify that the TValue inside the Collection is always a User model, you can use the @template tag in the docblock of your UserCollection class. Here's an example:
/**
* @template TValue of \App\Models\User
* @extends \Illuminate\Support\Collection<int, TValue>
*/
class UserCollection extends \Illuminate\Support\Collection
{
public function reserve()
{
return $this->each->doSomething();
}
}
In this example, we're using the @template tag to define a type parameter TValue that extends \App\Models\User. We're then using TValue as the type parameter for the parent Collection class.
With this docblock, PHPStorm should be able to resolve the type of $this->each as \App\Models\User.