在我使用 Symfony 4、Doctrine 2 和 PHP 7.2 的项目中,我有一个名为 Location 的实体和一个 LocationRepository(从 Doctrine 的 ServiceEntityRepository 扩展而来)。
我正在实现一个 findLocationByUuid 方法,其中给定一个字符串,返回一个位置:
public function getLocationByUuid(string $uuid): Location
{
$location = $this->findOneBy(['uuid' => $uuid]);
if (null == $location) {
throw new LocationNotFoundException();
}
return $location;
}
由于 Doctrine 的 findOneBy 方法返回一个 Object,那么严格符合方法中的返回类型声明并返回 Location 的最佳方法是什么? em> 而不是对象?我是否应该假设该对象与我的位置具有相同的行为并将对象声明为返回类型?
最佳答案
Symfony 4 ./bin/console make:entity 命令创建实体和存储库类。存储库类具有带注释的方法,如示例所示,因此您的问题应该得到解决
/**
* @method TinyPuppy|null find($id, $lockMode = null, $lockVersion = null)
* @method TinyPuppy|null findOneBy(array $criteria, array $orderBy = null)
* @method TinyPuppy[] findAll()
* @method TinyPuppy[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class TinyPuppyRepository extends ServiceEntityRepository
关于php - 强制存储库返回 CustomClass 类型而不是 Object 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48891275/