I made a small MVC Framework, but i need that my view Class can return the page as string but before that apply all the variables. How can this be done?
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;
}
}
Controller:
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)
}
so the htmlview will be a partial in regular indexView
Use output buffering
Example:
ob_start();
/* your error catch */
$render_html = ob_get_flush();
return $render_html;
Looks like you nee to get the file contents and replace all the variables there.
精彩评论