Symfony - 控制器



控制器負責處理進入 Symfony 應用程式的每個請求。控制器從請求中讀取資訊,然後建立並向客戶端返回響應物件。

根據 Symfony,DefaultController 類位於“src/AppBundle/Controller”。其定義如下。

DefaultController.php

<?php 
namespace AppBundle\Controller; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\Response;  

class DefaultController extends Controller {  
} 

這裡,HttpFoundation 元件為 HTTP 規範定義了一個面向物件的層,而FrameworkBundle 包含大部分“基礎”框架功能。

請求物件

Request 類是 HTTP 請求訊息的面向物件表示。

建立請求物件

可以使用createFromGlobals() 方法建立請求。

use Symfony\Component\HttpFoundation\Request; 
$request = Request::createFromGlobals();

您可以使用全域性變數模擬請求。除了基於 PHP 全域性變數建立請求外,您還可以模擬請求。

$request = Request::create( 
   '/student', 
   'GET', 
   array('name' => 'student1') 
);

這裡,create() 方法根據 URI、方法和一些引數建立請求。

覆蓋請求物件

您可以使用overrideGlobals() 方法覆蓋 PHP 全域性變數。其定義如下。

$request->overrideGlobals();

訪問請求物件

可以使用基控制器的getRequest() 方法在控制器(操作方法)中訪問網頁請求。

$request = $this->getRequest();

識別請求物件

如果您想在應用程式中識別請求,“PathInfo” 方法將返回請求 URL 的唯一標識。其定義如下。

$request->getPathInfo();

響應物件

控制器唯一的需求是返回一個 Response 物件。Response 物件儲存來自給定請求的所有資訊並將其傳送回客戶端。

以下是一個簡單的示例。

示例

use Symfony\Component\HttpFoundation\Response; 
$response = new Response(‘Default'.$name, 10);

您可以如下定義 JSON 格式的 Response 物件。

$response = new Response(json_encode(array('name' => $name))); 
$response->headers->set('Content-Type', 'application/json');

響應建構函式

建構函式包含三個引數:

  • 響應內容
  • 狀態程式碼
  • HTTP 頭陣列

以下是基本語法。

use Symfony\Component\HttpFoundation\Response;  
$response = new Response( 
   'Content', 
   Response::HTTP_OK, 
   array('content-type' => 'text/html') 
); 

例如,您可以將內容引數傳遞為:

$response->setContent(’Student details’);

同樣,您也可以傳遞其他引數。

傳送響應

您可以使用send() 方法向客戶端傳送響應。其定義如下。

$response->send();

要將客戶端重定向到另一個 URL,可以使用RedirectResponse 類。

其定義如下。

use Symfony\Component\HttpFoundation\RedirectResponse;  
$response = new RedirectResponse('https://tutorialspoint.tw/'); 

前端控制器

單個 PHP 檔案,處理進入應用程式的每個請求。前端控制器將不同 URL 的路由執行到應用程式的不同內部部分。

以下是前端控制器的基本語法。

use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response;  

$request = Request::createFromGlobals();  
$path = $request->getPathInfo(); // the URI path being requested 

if (in_array($path, array('', '/')))  { 
   $response = new Response(’Student home page.'); 
} elseif (‘/about’ === $path) { 
   $response = new Response(’Student details page’); 
} else { 
   $response = new Response('Page not found.', Response::HTTP_NOT_FOUND); 
} 
$response->send();

這裡,in_array() 函式在陣列中搜索特定值。

廣告
© . All rights reserved.