Search code examples
phpsymfonypsr-0

In Symfony2's "The Components -> The PSR-0 Class Loader" section which file(s) is being edited?


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?


Solution

  • 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.