1 回答

TA贡献1798条经验 获得超7个赞
欢迎使用StackOverflow!
首先,在调用时,getRepository()您必须传递实体类,而不是存储库本身,因此将是这样的:
$this->getDoctrine()->getRepository(Checklist::class);
即使这样做,您的IDE也不知道该方法存在。您的IDE实际上是错误的,该方法确实存在,您的IDE无法知道从getRepository()调用返回了什么对象。
如何避免呢?选择以下解决方案之一(它们都可以在PhpStorm中使用,选项1应该在任何地方都可以使用,选项2可能在所有现代IDE中都可以使用,我不知道其他IDE中对选项3的支持):
选项1:将其作为服务注入
public function myControllerRoute(ChecklistRepository $checklistRepository) {
// now your IDE knows what methods are inside the $checklistRepository
$items = $checklistRepository->getAllItemsForChecklist();
}
选项2:将其提示给IDE(和其他开发人员)
public function myControllerRoute() {
/** @var ChecklistRepository $checklistRepository */
$checklistRepository = $this->getDoctrine()->getRepository(Checklist::class);
// after the typehint the IDE knows what type it is
$items = $checklistRepository->getAllItemsForChecklist();
}
选项3:使用断言
public function myControllerRoute() {
$checklistRepository = $this->getDoctrine()->getRepository(Checklist::class);
assert($checklistRepository instanceof ChecklistRepository);
// after the assert the IDE knows what type it is
$items = $checklistRepository->getAllItemsForChecklist();
}
选项2和3几乎相同,但是选项3具有一个额外的好处,即在开发计算机上,如果$checklistRepository不是不是的实例,则它将抛出异常ChecklistRepository。在生产环境中,assert()调用将被忽略并且不会降低执行速度。
- 1 回答
- 0 关注
- 122 浏览
添加回答
举报