如何在不使用composer的情况下安装twig

Men*_*nno 3 php installation twig

我想为一个项目安装 twig,但没有对服务器的命令行访问权限。我只能通过 ftp 上传文件。这意味着我必须手动设置 twig lib,即自己创建 Autoload.php 文件。我已经彻底搜索过,但有关此主题的信息很少。我尝试了从另一个项目“借用”的以下自动加载,但这不会产生工作设置。

<?php

/*
 * This file is part of Twig.
 *
 * (c) 2009 Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Autoloads Twig classes.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Twig_Autoloader
{
    /**
     * Registers Twig_Autoloader as an SPL autoloader.
     *
     * @param bool    $prepend Whether to prepend the autoloader or not.
     */
    public static function register($prepend = false)
    {
        if (version_compare(phpversion(), '5.3.0', '>=')) {
            spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
        } else {
            spl_autoload_register(array(__CLASS__, 'autoload'));
        }
    }

    /**
     * Handles autoloading of classes.
     *
     * @param string $class A class name.
     */
    public static function autoload($class)
    {
        if (0 !== strpos($class, 'Twig')) {
            return;
        }

        if (is_file($file = dirname(__FILE__).'/../'.str_replace(array('_', "\0"), array('/', ''), $class).'.php')) {
            require $file;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

Car*_*los 7

  1. 下载树枝。(例如:https: //github.com/twigphp/Twig/archive/2.x.zip
  2. 将其提取到您想要的相对路径(例如:./Twig-2.x)。
  3. 将文件夹重命名Twig-2.x/srcTwig-2.x/Twig
  4. 将此 spl_autoload_register() 函数包含到您的引导脚本中。
  5. 记得使用 FQCN 来引用 Twig 的类

目录结构示例:

Appdir/
Appdir/Twig-2.x/
Appdir/Twig-2.x/Twig/ <- this is the original src dir renamed to Twig
Appdir/templates/
Appdir/templates/index.html
Appdir/cache/
Appdir/index.php
Run Code Online (Sandbox Code Playgroud)

代码“index.php”:

<?php

#ini_set('display_errors',1); # uncomment if you need debugging

spl_autoload_register(function ($classname) {
    $dirs = array (
        './Twig-2.x/' #./path/to/dir_where_src_renamed_to_Twig_is_in
    );

    foreach ($dirs as $dir) {
        $filename = $dir . str_replace('\\', '/', $classname) .'.php';
        if (file_exists($filename)) {
            require_once $filename;
            break;
        }
    }

});

$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [
    'cache' => 'cache',
]);

echo $twig->render('index.html', ['name' => 'Carlos']);

?>
Run Code Online (Sandbox Code Playgroud)

代码“index.html”:

<h1>Hello {{ name }}!</h1>
Run Code Online (Sandbox Code Playgroud)