加载名称空间所需的文件(使用不同的名称)


Load files needed by a namespace (with a different name)?

我有两个如下所述的文件:

路径:index . php

<?php
// Composer autload
require_once 'vendor/autoload.php';
//The commented code below works:
//$loader = new Twig_Loader_String();
//$twig = new Twig_Environment($loader);
//echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));
//Bad proposal solution. How to avoid to explicit load all files with namespaces?
//  Please see the 'Important edit' below.
//include_once 'Core/Twig/Twig.php';
use Core'Twig'Twig as Twig;
$twig = new Twig();
var_dump($twig);

路径:核心/理解/Twig.php

<?php
namespace Core'Twig;
class Twig
{
    public function configure()
    {
        $loader = new 'Twig_Loader_String();
        $twig = new 'Twig_Environment($loader);
        //just for testing
        echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));
    }
}

但是我得到一个致命错误:Class 'Core''Twig''Twig' not found .

我该如何解决这个问题?

注:我尝试了一些名称空间的变化(如Core'Twig, Core),使用(如Twig, Core'Twig, Core'Twig as Twig)和新的(如Twig'Twig(), Core'Twig)。不幸的是,什么都不行。

重要的编辑:我理解为什么php不定位类。需要include_once 'Core/Twig/Twig.php'这样的行。但问题仍然存在……我怎样才能避免这种情况呢?避免包含所有带有名称空间的文件?或者,我如何在需要时自动加载这些文件?

您可能错误地标记了名称空间。查看这个命名空间入门中的"命名空间导入:使用关键字"一节。

路径:lib/供应商/核心/Twig.php

<?php
namespace lib'vendor'core;
class Twig
{
    //Your code
}

路径:index . php

use lib'vendor'core'Twig;
$twig = new Twig();
var_dump($twig);

经过几次测试,我找到了答案。巡检vendor/autoload.php .

我们需要一些不明确的东西(至少对我来说)。

composer.json上我们需要添加

psr-0 : {
    "MyNamespace" : "MyOwnVendorName"
}
对于这种情况,应该运行以下代码:

Path: index.php

<?php
// Composer autload
require_once 'vendor/autoload.php';
use classes'MyApp'Twig'Twig;
$twig = new Twig;
var_dump($twig);

Path: core/classes/MyApp/Twig/Twig.php

<?php
namespace MyApp'Twig;
class Twig
{
    public function configure()
    {
        $loader = new 'Twig_Loader_String();
        $twig = new 'Twig_Environment($loader);
        //just for testing
        echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));
    }
}

composer.json

{
    "psr-0" : {
        "MyApp" : "core/classes/"
    }
}

然后运行php composer.phar udpate