1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 2 3 // ------------------------------------------------------------------------ 4 5 /** 6 * Output Class 7 * 8 * Output組件其實有不少有用的方法,不過通常狀況下,你不會直接去用到它們。 9 * 這裏主要以Output::_display_cache()和Output::_display()爲兩條主線來探究。 10 */ 11 class CI_Output { 12 13 /** 14 * Current output string 15 */ 16 protected $final_output; 17 18 19 /** 20 * Cache expiration time 21 */ 22 protected $cache_expiration = 0; 23 24 25 /** 26 * List of server headers 27 */ 28 protected $headers = array(); 29 30 31 /** 32 * List of mime types 33 */ 34 protected $mime_types = array(); 35 36 37 /** 38 * Determines wether profiler is enabled 39 */ 40 protected $enable_profiler = FALSE; 41 42 43 /** 44 * Determines if output compression is enabled 45 * @access protected 46 */ 47 protected $_zlib_oc = FALSE; 48 49 50 /** 51 * List of profiler sections 52 */ 53 protected $_profiler_sections = array(); 54 55 56 /** 57 * Whether or not to parse variables like {elapsed_time} and {memory_usage} 58 */ 59 protected $parse_exec_vars = TRUE; 60 61 /** 62 * Constructor 63 */ 64 function __construct() 65 { 66 $this->_zlib_oc = @ini_get('zlib.output_compression'); 67 68 if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) 69 { 70 include APPPATH.'config/'.ENVIRONMENT.'/mimes.php'; 71 } 72 else 73 { 74 include APPPATH.'config/mimes.php'; 75 } 76 77 78 $this->mime_types = $mimes; 79 80 log_message('debug', "Output Class Initialized"); 81 } 82 83 // -------------------------------------------------------------------- 84 85 /** 86 * Get Output 87 */ 88 function get_output() 89 { 90 //返回最終輸出。 91 return $this->final_output; 92 } 93 94 // -------------------------------------------------------------------- 95 96 /** 97 * Set Output 98 */ 99 function set_output($output) 100 { 101 //設置最終輸出。 102 $this->final_output = $output; 103 104 return $this; 105 } 106 107 // -------------------------------------------------------------------- 108 109 /** 110 * Append Output 111 */ 112 //經過此方法給Output::$final_output加上輸出內容,最終這些內容會在Output::_display()中被輸出。 113 //此方法在Loader.php中被調用。詳見Loader.php中的Loader::view()方法及Loader::_ci_load()方法。 114 function append_output($output) 115 { 116 if ($this->final_output == '') 117 { 118 $this->final_output = $output; 119 } 120 else 121 { 122 $this->final_output .= $output; 123 } 124 125 return $this; 126 } 127 128 // -------------------------------------------------------------------- 129 130 /** 131 * Set Header 132 */ 133 /** 134 * 接下來的三個方法都是設置頁面內容輸出前的頭信息。 135 */ 136 function set_header($header, $replace = TRUE) 137 { 138 if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0) 139 { 140 return; 141 } 142 143 $this->headers[] = array($header, $replace); 144 145 return $this; 146 } 147 148 // -------------------------------------------------------------------- 149 150 /** 151 * Set Content Type Header 152 */ 153 function set_content_type($mime_type) 154 { 155 if (strpos($mime_type, '/') === FALSE) 156 { 157 $extension = ltrim($mime_type, '.'); 158 159 if (isset($this->mime_types[$extension])) 160 { 161 $mime_type =& $this->mime_types[$extension]; 162 163 if (is_array($mime_type)) 164 { 165 $mime_type = current($mime_type); 166 } 167 } 168 } 169 170 $header = 'Content-Type: '.$mime_type; 171 172 $this->headers[] = array($header, TRUE); 173 174 return $this; 175 } 176 177 // -------------------------------------------------------------------- 178 179 /** 180 * Set HTTP Status Header 181 */ 182 function set_status_header($code = 200, $text = '') 183 { 184 set_status_header($code, $text); 185 186 return $this; 187 } 188 189 // -------------------------------------------------------------------- 190 191 /** 192 * Enable/disable Profiler 193 */ 194 //是否開啓評測器。 195 function enable_profiler($val = TRUE) 196 { 197 $this->enable_profiler = (is_bool($val)) ? $val : TRUE; 198 199 return $this; 200 } 201 202 // -------------------------------------------------------------------- 203 204 /** 205 * Set Profiler Sections 206 */ 207 function set_profiler_sections($sections) 208 { 209 foreach ($sections as $section => $enable) 210 { 211 $this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE; 212 } 213 214 return $this; 215 } 216 217 // -------------------------------------------------------------------- 218 219 /** 220 * Set Cache 221 */ 222 function cache($time) 223 { 224 //設置緩存時長。 225 $this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time; 226 227 return $this; 228 } 229 230 // -------------------------------------------------------------------- 231 232 /** 233 * Display Output 234 */ 235 function _display($output = '') 236 { 237 //爲何這裏要用global來調用這兩個組件呢?不是能夠經過$CI這個超級控制器來調用? 238 //其實就是由於這個_display方法,被調用的方式有兩種,其中有多是在CodeIgniter.php中調用 239 //Output::_display_cache();的時候間接被調用了,而此時& get_instance()這個方法壓根還沒 240 //被定義。詳見CodeIgniter.php中代碼定義和調用的順序。 241 global $BM, $CFG; 242 243 //固然若是能夠拿到超級控制器,咱們先拿過來。 244 if (class_exists('CI_Controller')) 245 { 246 $CI =& get_instance(); 247 } 248 249 // -------------------------------------------------------------------- 250 251 //若是$output爲空,其實每每這是非緩存方式調用的時候。咱們將使用Output::final_output。(若是是正常流程的輸出 252 //方式,而不是緩存的話,這個屬性其實在Loader::view()的時候調用Output::append_output()得到輸出內容。) 253 if ($output == '') 254 { 255 $output =& $this->final_output; 256 } 257 258 // -------------------------------------------------------------------- 259 260 //Output::$cache_expiration其實就是緩存時長,就是平時咱們在控制器裏面$this->output->cache(n)設置的時長 261 //現實手段就是使這個Output::$cache_expiration有必定的值,而後程序執行到這裏時根據此值判斷是否要緩存, 262 //若是要緩存就生成緩存文件。(注意若是是_display_cache間接調用的話,$this->cache_expiraton是必定爲0的,由於 263 //沒有經歷過在控制器中調用$this->output->cache(n)。) 264 if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output')) 265 { 266 //上面有個判斷$CI是否有_output方法,實際上是提供一個機會讓咱們自定義處理輸出。 267 //生成緩存文件。 268 $this->_write_cache($output); 269 } 270 271 // -------------------------------------------------------------------- 272 273 $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end'); 274 275 if ($this->parse_exec_vars === TRUE) 276 { 277 //系統的整體運行時間和內存消耗就是在這裏替換的。呵呵。上面的Output::$parse_exec_vars就是設置要不要替換。 278 $memory = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB'; 279 280 $output = str_replace('{elapsed_time}', $elapsed, $output); 281 $output = str_replace('{memory_usage}', $memory, $output); 282 } 283 284 // -------------------------------------------------------------------- 285 //壓縮傳輸的處理。 286 if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE) 287 { 288 if (extension_loaded('zlib')) 289 { 290 if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) 291 { 292 ob_start('ob_gzhandler'); 293 } 294 } 295 } 296 297 // -------------------------------------------------------------------- 298 if (count($this->headers) > 0) 299 { 300 foreach ($this->headers as $header) 301 { 302 @header($header[0], $header[1]); 303 } 304 } 305 306 // -------------------------------------------------------------------- 307 //若是沒有超級控制器,能夠證實當前是在處理一個緩存的輸出。不過利用這個方式來判斷,真的有點那個。。。 308 if ( ! isset($CI)) 309 { 310 echo $output;//輸出緩存內容。結束本函數。 311 log_message('debug', "Final output sent to browser"); 312 log_message('debug', "Total execution time: ".$elapsed); 313 return TRUE; 314 } 315 316 // -------------------------------------------------------------------- 317 //這裏是一個評測器,若是有開啓就調用,會生成一些報告到頁面尾部用於輔助咱們調試。我用CI的時候其實沒有開啓過,厄。 318 if ($this->enable_profiler == TRUE) 319 { 320 $CI->load->library('profiler'); 321 322 if ( ! empty($this->_profiler_sections)) 323 { 324 $CI->profiler->set_sections($this->_profiler_sections); 325 } 326 327 if (preg_match("|</body>.*?</html>|is", $output)) 328 { 329 $output = preg_replace("|</body>.*?</html>|is", '', $output); 330 $output .= $CI->profiler->run(); 331 $output .= '</body></html>'; 332 } 333 else 334 { 335 $output .= $CI->profiler->run(); 336 } 337 } 338 339 // -------------------------------------------------------------------- 340 341 //若是咱們有在當前的控制器裏面定義了_output這個方法,那麼能夠利用這個輸出作你想作的東西,這個也是很不錯的功能。 342 if (method_exists($CI, '_output')) 343 { 344 $CI->_output($output); 345 } 346 else 347 { 348 //若是沒有定義_output,就默認簡單輸出。 349 echo $output; // Send it to the browser! 350 } 351 352 log_message('debug', "Final output sent to browser"); 353 log_message('debug', "Total execution time: ".$elapsed); 354 } 355 356 // -------------------------------------------------------------------- 357 358 /** 359 * Write a Cache File 360 */ 361 /** 362 * 寫入緩存。在Output::_display()中,判斷須要緩存頁面時,則調用此方法寫入緩存。 363 */ 364 function _write_cache($output) 365 { 366 //下面不少操做其實和讀緩存的時候差很少。 367 368 $CI =& get_instance(); 369 $path = $CI->config->item('cache_path'); 370 371 $cache_path = ($path == '') ? APPPATH.'cache/' : $path; 372 373 if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path)) 374 { 375 log_message('error', "Unable to write cache file: ".$cache_path); 376 return; 377 } 378 379 $uri = $CI->config->item('base_url'). 380 $CI->config->item('index_page'). 381 $CI->uri->uri_string(); 382 383 $cache_path .= md5($uri); 384 385 if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE)) 386 { 387 log_message('error', "Unable to write cache file: ".$cache_path); 388 return; 389 } 390 391 //計算緩存文件過時時間。 392 $expire = time() + ($this->cache_expiration * 60); 393 394 if (flock($fp, LOCK_EX)) 395 { 396 //按CI的格式寫入緩存內容。 397 fwrite($fp, $expire.'TS--->'.$output); 398 flock($fp, LOCK_UN); 399 } 400 else 401 { 402 log_message('error', "Unable to secure a file lock for file at: ".$cache_path); 403 return; 404 } 405 fclose($fp); 406 @chmod($cache_path, FILE_WRITE_MODE); 407 408 log_message('debug', "Cache file written: ".$cache_path); 409 } 410 411 // -------------------------------------------------------------------- 412 413 /** 414 * Update/serve a cached file 415 */ 416 //在CodeIgniter.php裏面有調用此方法,此方法是負責緩存的輸出,若是在CodeIgniter.php中調用此方法有輸出,則 417 //本次請求的運行將直接結束,直接以緩存輸出做爲響應。 418 function _display_cache(&$CFG, &$URI) 419 { 420 //取得保存緩存的路徑 421 $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path'); 422 423 //一條準確的路由都會對應一個緩存文件,緩存文件是對應路由字符串的md5密文。 424 $uri = $CFG->item('base_url'). 425 $CFG->item('index_page'). 426 $URI->uri_string; 427 428 //計算出當前請求對應緩存文件的完整文件路徑。 429 $filepath = $cache_path.md5($uri); 430 431 //若是沒有此緩存文件,獲取緩存內容失敗,則能夠返回FALSE。 432 if ( ! @file_exists($filepath)) 433 { 434 return FALSE; 435 } 436 437 //若是有此緩存文件,可是沒法讀,獲取緩存內容失敗,一樣返回FALSE。 438 if ( ! $fp = @fopen($filepath, FOPEN_READ)) 439 { 440 return FALSE; 441 } 442 443 //打開到緩存文件,並以$fp做爲句柄。下一步先取得共享鎖(讀取)。 444 flock($fp, LOCK_SH); 445 446 //讀cache並保存到$cache中 447 $cache = ''; 448 if (filesize($filepath) > 0) 449 { 450 $cache = fread($fp, filesize($filepath)); 451 } 452 453 //解鎖 454 flock($fp, LOCK_UN); 455 //關閉文件鏈接。 456 fclose($fp); 457 458 //下面這個TS--->字樣,只是由於CI的緩存文件裏面的內容是規定以數字+TS--->開頭而已。這個數字是表明建立時間。 459 //若是不符合此結構,可視爲非CI的緩存文件,或者文件已損壞,獲取緩存內容失敗,返回FALSE。 460 //若是匹配成功,則$match[1]中保存的是"1346901048TS--->"字樣。其實在CI的這個版本$match[0]保存的是和 461 //$match[1]相同的內容,爲何要分開?我以爲是爲了之後擴展和方便改動吧,理解成 462 //$match[0]是除頁面內容以外的附加信息。 463 //$match[1]是附加信息中和時間有關的信息。 464 if ( ! preg_match("/(\d+TS--->)/", $cache, $match)) 465 { 466 return FALSE; 467 } 468 469 //去掉TS--->後,利用剩下的數字判斷緩存是否已通過期,若是過時了,就把它刪除,一樣視爲獲取緩存內容失敗(過時), 470 //返回FALSE 471 if (time() >= trim(str_replace('TS--->', '', $match['1']))) 472 { 473 if (is_really_writable($cache_path)) 474 { 475 @unlink($filepath); 476 log_message('debug', "Cache file has expired. File deleted"); 477 return FALSE; 478 } 479 } 480 481 //來到這裏,說明了可以順利得到緩存,則去掉附加信息($match[0])後,調用Output::_display()方法輸出緩存。並返回 482 $this->_display(str_replace($match['0'], '', $cache)); 483 log_message('debug', "Cache file is current. Sending it to browser."); 484 return TRUE; 485 } 486 487 488 }