【问题标题】:Load PHP code in PHP for delayed + parameterized execution?在 PHP 中加载 PHP 代码以延迟 + 参数化执行?
【发布时间】:2010-11-01 08:04:23
【问题描述】:

我有两个 PHP 文件:

  • template.php
  • template.html.php

第一个是 Template 的类定义。第二个包含一个实际的基于 HTML 的模板,但是带有 PHP 结构(因此是 .PHP 扩展名)。我称之为混合 html/php 文件。

是否可以在模板类 (special_include_parse()) 中创建一些函数,该函数需要:

  • $path(到一个混合的 html/php 文件)
  • $model(传递给混合 html/php 文件中的代码,以便可以使用 $this->getModel() 或 $model 或其他任何方式来引用它...)

?


template.php

class Template {
    function Parse($model) {
        //include('/var/www/template.html.php');
        //fopen('/var/www/template.html.php');
        $return = special_include_parse('/var/www/template.html.php', $model);
    }
}

template.html.php

<html>
    <head>
        <title><? echo $this->getModel()->getTitle(); ?></title>
    </head>
</html>

【问题讨论】:

标签: php templates class


【解决方案1】:

嗯...考虑到它基本上是 PHP 语法,为什么不直接设置 $this(尽管我不会这么称呼它)并包含/要求 template.html.php?基本上:

class Template {
  function Parse($model) {
    ob_start();
    require '/var/www/template.html.php'; // I wouldn't use absolute paths
    $return = ob_get_clean();
  }
}

虽然我个人认为这是一个典型的例子,它通过将不必要的(事实上,适得其反的)对象抽象引入到原本非常简单的事物中,从而使事情变得更加困难:

$model = new MyModel(...);
require 'template.html.php';

<html>...
  <h3><?= $model->getStuff(); ?></h3>

我不知道你为什么把它复杂化了,或者更确切地说你想达到什么目的。

【讨论】:

  • 我有视图类 (.php),它可以有一个链接的模板文件 (.html.php)。在脚本的末尾,在 View 类上调用 getHtml()。此时应该已经在 View 类上设置了一个模型。 Viewclass 需要以某种方式将该模型传递给它的模板,因此可以使用来自模型的值来解析模板。我认为输出缓冲实际上是我正在寻找的。你认为还有另一种更有效的方式来实现我想要的吗?
  • 您的视图是如何被调用或引用的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
相关资源
最近更新 更多