doumiao0498 2014-06-30 12:06
浏览 39
已采纳

在Symfony2的“组件 - > PSR-0类加载器”部分中正在编辑哪个文件?

I'm trying to grasp how to include a PSR-0 enabled external library on my Symfony2 project. In "The PSR-0 Class Loader" page (here: http://symfony.com/doc/master/components/class_loader/class_loader.html").

Which file is being edited? If it's app/autoloader.php, mine looks different than what's being presented:

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;
/**
 * @var $loader ClassLoader
 */
$loader = require __DIR__.'/../vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;

Do I have to include this code before return? Or it should be in the other files being called? Still if it's app/autoload.php, shouldn't this code:

// register several namespaces at once
$loader->addPrefixes(array(
    'Symfony' => __DIR__.'/../vendor/symfony/symfony/src',
    'Monolog' => __DIR__.'/../vendor/monolog/monolog/src',
));

be addNamespaces instead? and once I succeed in declaring this library how do I use it?

  • 写回答

1条回答 默认 最新

  • duanjie1339 2014-06-30 12:39
    关注

    Yes, notice that the app/autoload.php file fetches the $loader instance that is returned from vendor/autoload.php. So, the documentation you linked to gives an example where you explicitly create a new instance, but actually, using the app/autoload.php, the instance is ready and waiting for you.

    With regards to creating a new library set, let's assume I want to create a new library called 'MyLibrary', and it was going to live in the src directory, after:

    $loader = require __DIR__.'/../vendor/autoload.php';

    I would declare the following:

    $loader->addPrefix('MyLibrary', __DIR__.'/../src');

    Now I would:

    $ cd src

    $ mkdir MyLibrary

    $ mkdir MyLibrary/Component

    $ mkdir MyLibrary/Component/SomeClasses

    $ vim MyLibrary/Component/SomeClasses/MyClass.php

    MyClass.php:

    <?php
    
        namespace MyLibrary\Component\SomeClasses;
    
        class MyClass
        {
            ...
        }
    

    In another file wanting to use that class, at the top of the file, AFTER the namespace declaration (if there is one):

    <?php
    
    ...
    
    use MyLibrary\Component\SomeClasses\MyClass;
    
    $myClass = new MyClass();
    

    However, I have never found a need to do this so explicitly, as I would create a Symfony Bundle, which in effect is a library performing a specific task, and then put your code in the bundle. Creating a bundle is well documented.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!