2012-05-22 52 views
3

我最近查看了CodeIgniter的代碼,看看它是如何工作的。爲什麼CodeIgniter將輸出存儲在變量中?

我不明白的一件事是爲什麼CodeIgniter將視圖生成的所有輸出存儲在一個變量中,並在腳本的末尾輸出它?

下面是在線路870
CI Source code @ GitHub

/* 
* Flush the buffer... or buff the flusher? 
* 
* In order to permit views to be nested within 
* other views, we need to flush the content back out whenever 
* we are beyond the first level of output buffering so that 
* it can be seen and included properly by the first included 
* template and any subsequent ones. Oy! 
*/ 
if (ob_get_level() > $this->_ci_ob_level + 1) 
{ 
    ob_end_flush(); 
} 
else 
{ 
    $_ci_CI->output->append_output(ob_get_contents()); 
    @ob_end_clean(); 
} 

功能append_output追加給定字符串在CI_Output類的變量的一塊的從./system/core/Loader.php代碼。
是否有這樣做的特殊原因,而不是使用回聲陳述或只是個人喜好?

+1

這樣的問題不會更適合[CodeIgniter的論壇](http://codeigniter.com/forums/)嗎? – Quantastical

回答

4

答案是在你的文章的評論。

/** 
* In order to permit views to be nested within 
* other views, we need to flush the content back out whenever 
* we are beyond the first level of output buffering so that 
* it can be seen and included properly by the first included 
* template and any subsequent ones. Oy! 
*/ 

它是如此,你可以去:

$view = $this->load->view('myview', array('keys' => 'value'), true); 
$this->load->view('myotherview', array('data' => $view)); 
6

有幾個原因。上的原因是,可以加載的圖,並將它直接返回,而不是輸出:

// Don't print the output, store it in $content 
$content = $this->load->view('email-message', array('name' => 'Pockata'), TRUE); 
// Email the $content, parse it again, whatever 

第三個參數TRUE緩衝輸出,所以結果不打印到屏幕。如果沒有你就必須自己緩衝它:

ob_start(); 
$this->load->view('email-message', array('name' => 'Pockata')); 
$content = ob_get_clean(); 

另一個原因是,你不能設置頭已發送輸出之後,因此,例如,你可以通過用戶$this->output->set_content($content),再後來在某些時候設置的標頭(集內容類型標題,啓動會話,重定向頁面,等等),然後實際顯示(或不顯示)內容。

一般來說,我覺得它非常糟糕的形式有任何類或功能使用echoprint(在一個例子中在Wordpress中很常見)。我幾乎總是寧願使用echo $class->method();,因爲上面列出的原因相同,比如能夠將內容分配給變量,而不會直接泄漏到輸出或創建自己的輸出緩衝區。

+0

一般來說,對你的數據進行控制是很好的做法(擴展你的最後一段!)哦,我忘了電子郵件視圖部分,這是最常見的例子! –

+0

對於一個普通的例子'功能問候($ str){echo「Hello $ str!」;}'...'echo strtolower(greet('Andrew'));'< - 不起作用,如果函數'return'ed。對''this-> load-> view()''''echo'有意義,但並不是每次用Output類設置一點輸出。 –

+0

這是我的觀點哈哈!它可以更好地控制如何處理數據 –