一次 HTTP 請求在 Symfony2 中的流轉:
Request 對象封裝 Header、GET、POST 數據等Response 對象封裝頁面、JSON、重定向等$request = $this->getRequest(); // 獲取 Request 對象
// 獲取參數
$request->query->get('param'); // GET 參數
$request->request->get('param'); // POST 參數
$request->attributes->get('id'); // 路由參數
$request->headers->get('User-Agent'); // Header
$request->files->get('avatar'); // 上傳檔案
$request->cookies->get('session_id'); // Cookie
$request->getMethod(); // HTTP 方法
$request->getRequestFormat(); // 請求格式
現代化命令列 HTTP 客戶端,極適合 API 測試:
# 安裝參考:https://blog.csdn.net/pzw_0612/article/details/46521965
# 模擬表單 POST 提交
http -f post https://localhost:8000/app_dev.php/page/test name=lily
<?php
namespace Scource\WebBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
class DefaultController extends Controller {
/**
* @Route("/page/test1")
*/
public function test1Action() {
// 1. 純文字/HTML 直接輸出
return new Response('11111111111');
// 2. JSON 返回(API 常用)
// return new JsonResponse(array('a' => 'abcdef'));
// 3. 重定向
// return new RedirectResponse('https://www.cnblogs.com/tianxintian22/');
}
}
| Response 類型 | Content-Type | 適用場景 |
|---|---|---|
| Response | text/html | 頁面渲染、純文字 |
| JsonResponse | application/json | REST API、AJAX 回應 |
| RedirectResponse | text/html + Location | 頁面跳轉、POST-Redirect-GET |
$session = $this->getRequest()->getSession();
// 寫入
$session->set('b', 'ni hao!');
// 讀取
$value = $session->get('b');
// 判斷存在
$session->has('b');
// 移除
$session->remove('b');
// 清空
$session->clear();
若 Session 讀寫異常,檢查 app/cache/dev 目錄權限:
chmod -R 777 app/cache/dev
# 或確保 Web Server 用戶有讀寫權限
適用於表單提交後的成功/錯誤提示:
Controller 端設置
$this->getRequest()->getSession()->getFlashBag()->add('notice', 'you have something wrong');
Twig 模板顯示
{% for flashMessage in app.session.flashbag.get('notice') %}
<div class="flash-notice">
{{ flashMessage }}
</div>
{% endfor %}
Flash Message 讀取一次即自動銷毀,完美適配「提交→重定向→顯示提示」模式。
JsonResponse 規範 API 返回格式RequestStack 替代 getRequest()(Symfony 2.4+ 推薦)@Route 註解簡化路由配置ParamConverter 自動轉換路由參數為實體對象Symfony2 的 Request/Response/Session 設計極具現代 Web 框架風範,掌握其核心用法能顯著提升開發效率與代碼質量。