RenderToHtml viewfile и вернуть строку? - PullRequest
0 голосов
/ 22 ноября 2010

Я сделал небольшой MVC Framework, но мне нужно, чтобы мой класс представления мог возвращать страницу в виде строки, но перед этим применяются все переменные. Как это может быть сделано?

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

Ответы [ 2 ]

1 голос
/ 22 ноября 2010

Использование выходной буферизации

Пример:

ob_start();
/* your error catch */
$render_html = ob_get_flush();
return $render_html;
0 голосов
/ 22 ноября 2010

Похоже, вы должны получить содержимое файла и заменить все переменные там.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...