3

私は最近、CodeIgniter のコードを調べて、それがどのように機能するかを確認しました。

私が理解できないことの 1 つは、CodeIgniter がビューによって生成されたすべての出力を単一の変数に格納し、スクリプトの最後に出力する理由です。

./system/core/Loader.php の 870 行目のコードを次に示します
CI ソース コード @ 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 クラスの変数に追加します。
これを行い、echo ステートメントを使用しない特別な理由はありますか、それとも単なる個人的な好みですか?

4

2 に答える 2

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

3番目のパラメーターTRUEは出力をバッファーに入れて、結果が画面に出力されないようにします。自分でバッファリングする必要がない場合:

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

もう1つの理由は、出力を送信した後にヘッダーを設定できないことです。たとえば、ユーザー$this->output->set_content($content)は、その後、ある時点でヘッダーを設定し(コンテンツタイプのヘッダーを設定し、セッションを開始し、ページをリダイレクトするなど)、実際に表示(またはコンテンツを表示しないでください)。

echo一般的に、クラスや関数を使用するのは非常に悪い形式だと思いますprint(たとえば、Wordpressでは一般的です)。echo $class->method();上記で概説したのと同じ理由で、出力に直接流出することなくコンテンツを変数に割り当てることができる、または独自の出力バッファーを作成するなどの理由で、ほとんどの場合、エコーさせるよりも使用したいと思います。

于 2012-05-22T19:13:33.297 に答える
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));
于 2012-05-22T19:12:58.303 に答える