In almost all tutorials or answers on SO, I see a common way to send data from a Controller to the View, the class View often looks something similar than the code below:
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;
}
}
I don't understand why I need to put the data in an array and then call extract($this->_data). Why not just put directly some properties to the view from the controller like
$this->_view->title = 'hello world';
then in my layout or template file I could just do:
echo $this->title;