PHP 视图,使用模板

3 php templates output-buffering

好吧,我的问题很简单,但有点难以接受解决方案,但无论如何..如下,我有一个“ mini-framework”,需要编写单个方案的东西,对我有很大帮助,加速了一些工作然而,问题是,即使对于视图,在某种程度上,使用模板方案也非常简单,也非常有趣,因为当您必须更改任何内容时related to visualization,模板只会更改,但是,及时render this template,这就是最好的办法?我目前正在这样工作:

<?php

          class View {

                 private $vars;

                 public function __get ( $var ) {
                        if ( isset( $this->vars [ $var ] ) ) {
                               return $this->vars[ $var ];
                        }
                 }

                 public function assign ( $var , $value ) {
                        $this->vars [ $var ] = $value;
                 }

                 public function show ( $template ) {
                        include_once sprintf ( "%s\Templates\%s" , __DIR__ , $template ) ;
                 }

          }
Run Code Online (Sandbox Code Playgroud)

这不是完整的代码,我正在构建结构并审查该方案,所以我执行以下操作..

<?php
          require_once 'MVC/Views/View.php';
          $View = new View ( ) ;

          $View->assign( 'title' , 'MVC, View Layer' ) ;
          $View->show ( 'test.phtml' );
Run Code Online (Sandbox Code Playgroud)

还有模板

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
       <head>
              <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
              <title><?php echo $this->title ?></title>
       </head>
       <body>

       </body>
</html>
Run Code Online (Sandbox Code Playgroud)

输出是正确的all working as expected,但我的问题是:这是最好的方法吗?包含文件并让游戏解释编写的代码.phtml

Ald*_*nio 5

在很多框架中我都看到过这样的说法:

public function show ( $template ) {
  ob_start();
  require sprintf ( "%s\Templates\%s" , __DIR__ , $template ) ;
  return ob_get_flush();
}
Run Code Online (Sandbox Code Playgroud)

使用输出缓冲区,您可以将模板计算为字符串,而不是直接在输出中发送。当您需要在评估模板后更改标题或进行后处理时,这会很方便。

使用 require 而不是 include_once 将允许您多次渲染相同的模板(例如,如果您想要某种模板组合),并且如果找不到模板文件,则会收到错误(include 不会给出错误)情况)。