简体   繁体   English

平文件站点:没有数据库的PHP5主模板

[英]FLAT FILE SITE: PHP5 Master Template Without Database

Dear folks, Imagine a flat php site without database with hundreds of files having the same variables defined in all of them eg $read $look and $buys . 亲爱的人们,想象一下一个没有数据库的扁平php网站,其中包含数百个在所有文件中定义相同变量的文件,例如$read $look$buys

page1.php page1.php

<?
$blue= ".....";
$bell= ".....";
$beam= ".....";
?>

page2.php page2.php

<?
$blue= ".....";
$bell= ".....";
$beam= ".....";
?>

etcettera.php etcettera.php

Now, as soon as I invent a new variable, say $bike or $beaf then I have to go through all those template files in order to add to them $beaf = "" or else there undefined there. 现在,一旦我发明了一个新变量,比如说$bike$beaf那么我就必须遍历所有这些模板文件,以便向它们添加$beaf = "" ,否则就在那里没有定义。 I miss a master template so to say... Any ideas/hints/code/suggestions are welcome. 我想念一个主模板,所以...欢迎任何想法/提示/代码/建议。 Thanks in advance. 提前致谢。

Is there any smarter way of template management without use of database, making it easer to maintain these templates? 在不使用数据库的情况下,有没有更聪明的模板管理方法,可以更轻松地维护这些模板?

A templating engine like Twig might help you. Twig这样的模板引擎可能会为您提供帮助。 Twig supports template inheritance , which allows you to define a master template that all child templates inherit from: Twig支持模板继承 ,它允许您定义所有子模板都继承自的主模板:

master.html.twig: master.html.twig:

<html>
  <head><title>{% block title %}Default Title{% endblock %}</title></head>
  <body>
    <h1>{% block pageHeading}{% endblock %}</h1>
    {% block body}{% endblock %}
  </body>
</html>

child.html.twig: child.html.twig:

{% extends master.html.twig %}
{% block title}Child Page{% endblock %}
{% block pageHeading}Weclome!{% endblock %}
{% block body}
<p>My name is {{ name }}.  Today's date is {{ today|date('n/j/Y') }}.</p>
{% endblock %}

PHP code: PHP代码:

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
  'cache' => '/path/to/compilation_cache',
));
$template = $twig->loadTemplate('child.html.twig');
echo $templater->render(array("name"=>"Mike", "today"=>new DateTime()));

I would suggest to create a file that has an __autoload function in it, include it at the top of your page1.php (and so on), then create some class like this: 我建议创建一个其中具有__autoload函数的文件,将其includepage1.php的顶部(依此类推),然后创建这样的类:

class MyVars {
  const book = "Book";
  const apple = "Apple";
}

and you can use them like MyVars::book and MyVars::apple in your PHP files. 您可以在PHP文件中使用它们,例如MyVars::bookMyVars::apple

Your system with flat variables floating around is one of the thing to avoid. 带有平面变量的系统是要避免的事情之一。

Use a framework that helps you not doing such bad errors or just use Smarty 使用可以帮助您避免发生此类错误或仅使用Smarty的框架

Zend 曾德

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM