Ale*_*lex 5 php templates lazy-loading
目前我这样做:
function load_template($script, $args){
extract($args);
require __DIR__ . '/templates/' . $script;
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器代码中:
// if home page was requested
load_template('home.php', array(
'title' => get_title(),
'content' => get_content(),
...
));
Run Code Online (Sandbox Code Playgroud)
该模板只是一个PHP脚本
<!DOCTYPE html>
<html>
<head>
<title> <?php echo $title; ?> </titlee>
...
Run Code Online (Sandbox Code Playgroud)
我想知道是否有可能以某种方式延迟加载这些变量,所以我实际上并没有运行get_title()
或get_content()
直到模板专门请求变量.
如果没有创建模板解析器,这可能是可能的吗?我真的很想坚持使用简单的.php脚本和html作为模板.
简而言之,我要问的是,是否可以仅在首次请求时自动为变量赋值.
$var = func(); // this should not run
if($var){ // now the code above should run:)
echo $var; // <- the value that was just assigned (don't run func() again)
}
Run Code Online (Sandbox Code Playgroud)
在我看来,如果您不想更改模板来提取变量,您可以创建一个数组,该数组将知道每个模板需要哪些变量。
您可以考虑一个函数(我们将其命名为caller
),向其中传递所有参数和模板名称。他们caller
可以选择需要哪些变量。这个想法就像oop中的工厂类。
我认为没有其他办法,但是...
插入模板并使用不存在的变量时,将显示警告。您可以让 PHP 在警告中抛出异常,然后在try ... catch
块中解析它。我认为这太复杂了,不值得付出努力。
编辑
第三个想法是创建对象而不是数组。该对象将保留您的所有$args
变量。在您的模板中只需更改<?php echo $title; ?>
为<?php echo $argument_object->getTitle(); ?>
,并对getTitle()
方法进行编码。作为方法getTitle()
而不是函数,将仅根据请求运行。