博客 / 詳情

返回

Symfony筆記之--控制器的快捷方法

Shortcuts methods in Controller

1. 獲取服務

    $this->get($serviceId);

2. 重定向

    
    $this->redirectToRoute($routeName, $parameters, $status = 302);

3. 生成路由的url

    $this->generateUrl($routeName, $parameters, $referenceType);

4. 返回一個json response

    
    $this->json($data, $status = 200, $headers = array(), $context = array());

5. 添加一個flash message

    $this->addFlash($type, $message);

6. 判斷是否授權進入某個方法

    $this->isGranted('ROLE_ADMIN');

7. 判斷用户是否授權,否,拋出異常


    $this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');

8. 手動判斷 CSRF token是否合法

    $this->isCsrfTokenValid('token_id', $token);

9. 把請求轉發到其他控制器和方法

    $this->forward('GregwarCaptchaBundle:Captcha:generateCaptcha', ['key' => $key]);
    //forward($controller, array $path = array(), array $query = array())

PS: 第二個參數為route上佔位符參數,第三個為其他額外的參數

10. 文件下載(symfony >= 3.2)

    $this->file();

    //簡單用法示例
     return $this->file($docPath, $saveName); 
     // 如果是pdf之類,直接顯示而不是下載,需要設置第三個參數ResponseHeaderBag::DISPOSITION_INLINE
    // 還可以直接接受一個File或者UploadedFile實例
    //$samplePdf = new File('/sample.pdf');
    //return $this->file($samplePdf);

11. 讀取配置參數

    $this->getParameter('kernel.root_dir');
user avatar konstantinos-kouratoras 頭像 abei2017 頭像 mozhong_5eddab49b9d32 頭像 philip-tellis 頭像 zuiyuesi 頭像 admim 頭像 huangzhhui 頭像 aoshunseo 頭像 jervain 頭像 mowangjuanzi 頭像 windysay 頭像 heyiming 頭像
23 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.