I'm trying to implement something like the Repository of Doctrine does. I do not interact with a database but need to fetch data from sources.
I have an AbstractRepository and want to have an autocompletion in PhpStorm based on the class given in the constructor. Here is some code:
/**
* @template T
*/
abstract class AbstractRepository
{
/**
* @psalm-var class-string<T>
*/
protected $className;
public function __construct(string $className)
{
$this->className = $className;
}
/*
* @psalm-return ?T
*/
public function findById(string $id)
{
// do some calls and return an actual model based on the classname
}
}
class FooRepository extends AbstractRepository
{
public function __construct()
{
parent::__construct(MyModel::class);
}
}
(new FooRepository())->findById('bar'); // PHPStorm should typehint as MyModel
But PhpStorm just says mixed|null.
What am I doing wrong?
With PHPStorm, you have to use the DynamicReturnTypePlugin to get the autocompletion on return types depending on the function parameters.
https://plugins.jetbrains.com/plugin/7251-dynamicreturntypeplugin