PHP视图,使用模板


PHP View, working with templates

好吧,我的问题很简单,但有点难以接受的解决方案,但无论如何…下面是,我有一个' 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 ) ;
                 }
          }

这不是完整的代码,我正在构建结构并检查方案,所以我做了以下操作:

<?php
          require_once 'MVC/Views/View.php';
          $View = new View ( ) ;
          $View->assign( 'title' , 'MVC, View Layer' ) ;
          $View->show ( 'test.phtml' );

和模板

<!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>

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

中编写的代码

在很多框架中我都看到过这样的语句:

public function show ( $template ) {
  ob_start();
  require sprintf ( "%s'Templates'%s" , __DIR__ , $template ) ;
  return ob_get_flush();
}

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

使用require而不是include_once将允许你多次呈现相同的模板(例如,如果你想有某种模板组合),并且在模板文件未找到时得到一个错误(在这种情况下,include不会给出错误)