CodeIgniter 使用手冊版本 2.1.4


Output 類別

Output 類別是一個小類別,其主要的功能是:將最終產生的網頁送交給客戶端瀏覽器。 若你使用了快取的功能,它也負責快取你的網頁。

注意:系統會自動初始這個類別, 所以不需要手動載入。

在一般的情況下你不會發現 Output 類別,因為它不需要你的介入便默默的在工作。 例如,當你使用 Loader 類別去讀取一個 view 檔案,這個 view 檔案會被自動的傳給 Output 類別, 然後在系統執行的最後階段 CodeIgniter 會自動處理這些輸出步驟。當然,必要的話你也可以手動的去處理,只要使用下列兩個函式:

$this->output->set_output();

允許你手動設定最後輸出的字串。使用範例:

$this->output->set_output($data);

非常重要:如果你要自己操作輸出的功能,則必須放在最後一個步驟才做。 例如,如果你正在你的一個 controller 函式中建立頁面,你只能在函式最後結束前才能使用output。

$this->output->set_content_type();

允許你設定頁面的 mime-type,如此一來你可以更輕鬆的提供 JSON、JPEG 及 XML 等等資料。

$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => 'bar')));

$this->output
    ->set_content_type('jpeg') // 你也可以使用 ".jpeg","點號"會先被移掉才去查找 config/mimes.php
    ->set_output(file_get_contents('files/something.jpg'));

非常重要:確認你傳入的所有非mine的字串都有在 config/mimes.php 中設定好,否則不會運作。

$this->output->get_output();

允許你手動取回 Output 類別所存放的輸出資料。使用範例:

$string = $this->output->get_output();

注意,只有在使用了像是 $this->load->view() 這樣的函式來將資料傳送給 Output 類別以後,你才能夠從 Output 類別取得輸出資料。

$this->output->append_output();

增加資料到輸出字串中。使用範例:

$this->output->append_output($data);

$this->output->set_header();

允許你手動設定 HTTP header,這將在 Output 類別準備好頁面要輸出時一併送出。參考範例:

$this->output->set_header("HTTP/1.0 200 OK");
$this->output->set_header("HTTP/1.1 200 OK");
$this->output->set_header('Last-Modified: '.gmdate('D,d M Y H:i:s',$last_update).' GMT');
$this->output->set_header("Cache-Control: no-store,no-cache,must-revalidate");
$this->output->set_header("Cache-Control: post-check=0,pre-check=0");
$this->output->set_header("Pragma: no-cache");

$this->output->set_status_header();

允許你手動設定 HTTP status。參考範例:

$this->output->set_status_header('401');
// 設定 header: Unauthorized

請參考:完整的 header 列表

$this->output->enable_profiler();

允許你啟用或停用 Profiler,這會在你的頁面底部顯示一些資料與數據,可以用來除錯或是最佳化。

若要啟用 Profiler,將下面的函式放在你的 Controller 當中任意地方。

$this->output->enable_profiler(TRUE);

當啟用之後,在你的網頁底部將會插入一些報表。

若要停用 Profiler 你可以這樣做:

$this->output->enable_profiler(FALSE);

$this->output->set_profiler_sections();

允許你啟用或停用 Profiler 特定的部份,請參考 Profiler 的文件 以取得更多資訊。

$this->output->cache();

CodeIgniter 輸出函式庫也可以控制快取,請參考caching 的文件

解析變數

CodeIgniter 預設會在輸出中解析這些虛擬變數:{elapsed_time}{memory_usage}。 要停用這項功能,將 controller 的類別屬性$parse_exec_vars 設定為 FALSE

$this->output->parse_exec_vars = FALSE;