【问题标题】:PHP View, working with templatesPHP 视图,使用模板
【发布时间】:2011-12-05 14:03:40
【问题描述】:

好吧,我的问题很简单,但有点难以接受解决方案,但无论如何.. 如下,我有一个'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中写的代码

【问题讨论】:

    标签: php templates output-buffering


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 输出缓冲区很有用,因为它让您有机会更改模板的输出或在多个模板的组合中使用它。此外,如果您不缓冲输出,则在运行 show 方法后,您将无法再更改响应标头。
    猜你喜欢
    • 2019-03-04
    • 2016-09-16
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2011-02-20
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多