SOに関するほとんどすべてのチュートリアルまたは回答で、コントローラーからビューにデータを送信する一般的な方法を確認します。クラス ビューは、多くの場合、以下のコードに似たものになります。
class View
{
protected $_file;
protected $_data = array();
public function __construct($file)
{
$this->_file = $file;
}
public function set($key, $value)
{
$this->_data[$key] = $value;
}
public function get($key)
{
return $this->_data[$key];
}
public function output()
{
if (!file_exists($this->_file))
{
throw new Exception("Template " . $this->_file . " doesn't exist.");
}
extract($this->_data);
ob_start();
include($this->_file);
$output = ob_get_contents();
ob_end_clean();
echo $output;
}
}
データを配列に入れてから、extract($this->_data) を呼び出す必要がある理由がわかりません。コントローラーからいくつかのプロパティをビューに直接配置しないのはなぜですか
$this->_view->title = 'hello world';
次に、レイアウトまたはテンプレートファイルで次のことができます。
echo $this->title;