[英]How to set custom headers in all methods of a Symfony 4 Controller with FOSRestBundle?
[英]Symfony | How to access the custom methods from the respository in a controller?
我正在建立一個清單,以練習使用Symfony構建Web應用程序。 通過將字符串輸入表單並按下提交按鈕來工作。 輸入存儲在數據庫中。
我想將數據庫中存儲的輸入返回到網頁。
當前,輸入存儲在數據庫中,並且我已經在存儲庫中編寫了DQL查詢功能。
我的問題是我無法訪問在控制器中創建的方法。
我的存儲庫中的方法:
/**
* @return Checklist[]
*/
public function getAllItemsForChecklist(): array
{
$qb = $this->createQueryBuilder('c')
->select('item')
->from('checklist', 'x')
->getQuery()
;
return $qb->execute();
}
嘗試訪問控制器中方法的行(失敗):
$items = $this->getDoctrine()
->getRepository(ChecklistRepository::class)
->getAllItemsForChecklist()
;
根據https://symfony.com/doc/master/doctrine.html#querying-for-objects-the-repository上的Symfony文檔,這應該可以工作。 但是,找不到方法“ getAllItemsForChecklist()。在我的IDE上給出以下消息:
在\\ Doctrine \\ Common \\ Persistence \\ ObjectRepository中找不到方法'getAllItemsForChecklist'
我不確定為什么它沒有讀取我指定的存儲庫類。
如果有人知道如何解決此問題,那么它將在我的存儲庫中找到我所贊賞的方法。
另外,如果需要任何其他信息,請告訴我我很樂意提供更多信息。
問候,
史蒂夫
歡迎來到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()
調用將被忽略並且不會減慢執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.