我制作了一个小型的MVC框架,但是我需要我的view类能够以字符串的形式返回页面,但是在这之前应用所有的变量。怎么能做到?
class View{
private $registry;
private $vars = array();
private $file;
public function __set($index, $value){
$this->vars[$index] = $value;
}
public function __construct($controller, $action){
$this->file = "Views/".$controller."/".$action.".php";
$this->registry = new Registry();
}
public function renderToHtml(){
try{
if(file_exists($this->file)){
foreach ($this->vars as $key => $value){
$$key = $value;
}
/** include $this->file; **/
//apply vars on file
return $html;
}else{
throw new Exception("No such View file");
}
}catch (Exception $e) {
echo '<h1>Caught exception: ', $e->getMessage(), "</h1>";
exit;
}
}
控制器:
public function indexAction(){
$html = new View('SomeController', 'htmlview');
$html->somevar = "blabla";
$this->View->fubar = $html->renderToHtml();
$this->View->render() //this will render the current action/view (index)
}
所以htmlview将是正则indexView中的一部分