視圖層負責資料呈現,核心功能包含:模板渲染、輸出緩衝控制、佈局支援、裝置適配(PC/WAP)。
<?php
class view {
public static $view_type = null;
public function __construct() {
ob_start(); // 開啟輸出緩衝
}
// 取得緩衝內容並清空
public function finish() {
$content = ob_get_contents();
return $content;
}
// 自動偵測裝置類型
public static function set_view_type() {
switch (true) {
case stripos($_SERVER['HTTP_USER_AGENT'], 'Windows CE') !== FALSE:
self::$view_type = 'wap';
break;
default:
self::$view_type = 'default';
}
}
// 核心渲染方法
public static function show($location, $param = array()) {
if (is_null(self::$view_type)) {
self::set_view_type();
}
$view = SIMPLE_PATH . '/view/' . self::$view_type . '/' . $location;
extract($param, EXTR_OVERWRITE); // 變數解包至當前作用域
ob_start();
file_exists($view) ? require $view : exit($view . ' 不存在');
$content = ob_get_contents();
return $content;
}
}
核心概念:PHP 預設直接輸出至瀏覽器,OB 機制將輸出暫存記憶體緩衝區,允許程式碼操作輸出內容。
| 函數 | 說明 |
|---|---|
ob_start() | 開啟輸出緩衝,後續輸出寫入緩衝區 |
ob_get_contents() | 取得緩衝區內容(字串),不清空緩衝區 |
ob_get_clean() | 取得內容並關閉/清空緩衝區 |
ob_end_flush() | 輸出緩衝區內容並關閉緩衝 |
ob_end_clean() | 清空緩衝區並關閉,不輸出 |