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

时间:2013-03-24 14:15:31

标签: php class namespaces

我有两个文件如下所述:

路径: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);

路径:Core / 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

我该如何解决这个问题?

PS:我尝试过命名空间的一些变体(例如Core\TwigCore),使用(例如TwigCore\TwigCore\Twig as Twig)和新的(如Twig\Twig()Core\Twig)。不幸的是,没有任何作用。

重要编辑: 我明白为什么php没有找到这个类。需要像include_once 'Core/Twig/Twig.php'这样的行。但问题仍然存在......我怎么能避免这种情况?避免包含具有命名空间的所有文件?或者,如何在需要时自动加载此文件?

2 个答案:

答案 0 :(得分:2)

您可能错误地标记了命名空间。查看“命名空间导入:使用关键字”部分in this namespace primer.

路径:lib / vendor / core / Twig.php

<?php
namespace lib\vendor\core;

class Twig
{
    //Your code
}

路径:index.php

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

答案 1 :(得分:0)

经过几次测试,我得到了答案。检查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

相关问题