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

问题描述 投票:0回答:3

我想为项目安装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 <[email protected]>
 */
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;
        }
    }
}

任何帮助,将不胜感激。

php installation twig
3个回答
0
投票

如果你真的需要加载没有Composer的Twig,你可以使用:https://gist.github.com/sarciszewski/b6cd3776fbd20acaf26b

我建议在本地开发环境中设置Composer。 (您可以从https://getcomposer.org/下载)使用Composer安装twig。

composer require twig/twig:~2.0

然后在您的项目中包含自动加载器:

require_once 'vendor/autoload.php';

您可以在本地工作,当项目准备就绪时,使用包含已安装软件包的供应商目录部署到您的服务器。您的服务器上不需要composer。


0
投票

在研究了András提供的链接后,我意识到关键不是加载机制,而是“autoload.php”似乎缺失的事实。我发现,我正在使用的Twig版本,实际上是一个2.X版本,至少需要PHP 7.因为我使用5.4,显然这不起作用。幸运的是,最新的1.X版本的lib确实提供了autoload.php,所以从那里一切正常。


0
投票
  1. 下载Twig。 (来自前者:https://github.com/twigphp/Twig/archive/2.x.zip
  2. 将其提取到您想要的相对路径(例如:./ Turig-2.x)。
  3. Twig-2.x/src文件夹重命名为Twig-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

代码“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']);

?>

代码“index.html”:

<h1>Hello {{ name }}!</h1>
© www.soinside.com 2019 - 2024. All rights reserved.