包括来自外部文件的树枝加载器

2022-01-22 00:00:00 php twig

我目前将这个包含在每个控制器文件的顶部:

I am currently including this at the top of every controller file:

$loader = new Twig_Loader_Filesystem('/templatedir/templates');

$twig = new Twig_Environment($loader, array('debug' => true));
$twig->addExtension(new Twig_Extension_Debug());

我发现将它放在每个文件中有点多余.将此代码放在外部文件中并将其包含在 require_once 命令中会有任何问题吗?

I find that placing this in every single file a bit redundant. Will there be any issues with placing this code in an external file and including it with a require_once command?

每个控制器文件中的 render 语句将使用外部文件中包含的 $twig 变量.从另一个文件访问变量我有点不舒服,但我想知道我的担忧是否合理.

The render statement which follows in each controller file would make use of the $twig variable being included from the external file. I am a bit uncomfortable with accessing a variable from another file but am wondering if my concerns are justified.

推荐答案

对于简单的应用程序来说,使用 require_once 没问题.您的担忧当然是对的,如果变量 $twig 也设置在其他地方,在另一个包含和另一个上下文中怎么办?您将遇到难以调试的冲突.

To use require_once ist fine for a simple application. Your concerns are of course right, what if the variable $twig is set somewhere else too, in another include and another context? You would have a collision that is hard to debug.

有几种方法可以避免这个问题.如果你熟悉面向对象编程,你可以这样定义一个类:

There are several ways to avoid this problem. If you are familiar with object oriented programming, you could define a class like this:

文件 Twigloader.php

File Twigloader.php

class Twigloader {
  public static $twig;

  public static function init() {
    $loader = new Twig_Loader_Filesystem('/templatedir/templates');

    self::$twig = new Twig_Environment($loader, array('debug' => true));
    self::$twig->addExtension(new Twig_Extension_Debug());
  }
}

Twigloader::init();

现在,在您需要树枝的每个文件中,您可以执行以下操作而不会发生碰撞:

Now in each file you need twig you can do the following without the risk of a collision:

require_once "Twigloader.php";
$template = Twigloader::$twig->loadTemplate('test.html');

如果您不喜欢 require_once,因为在复杂的应用程序中很难跟踪不同的依赖关系,您应该考虑自动加载:http://php.net/manual/de/language.oop5.autoload.php

If you don't like require_once because in a complex application it is hard to keep track on the different dependencies you should look into autoloading: http://php.net/manual/de/language.oop5.autoload.php

相关文章