Search code examples
phpautoloaderpsr-0symfony-components

Symfony ClassLoader Component example


I'm trying to set up a simple example in order to understand how the ClassLoader Component of Symfony and the new PSR-0 standard work.

First I created Bar.php:

namespace Acme;

class Bar 
{
    // Implementation
    public static function helloWorld() {
        echo "Hello world!";
    }
}

Then I created a autoloader.php (under the vendor path I have the ClassLoader component):

require_once __DIR__.'/vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php';

use Symfony\Component\ClassLoader\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->register();

$loader->registerNamespace('Acme', __DIR__);

Lastly I created Foo.php:

require_once 'autoloader.php';

use Acme;

class Foo extends Bar
{
    // Implementation
}

$foo = new Foo();
$foo::helloWorld();

But when I execute:

$ php Foo.php

I get the following error message:

PHP Warning: The use statement with non-compound name 'Acme' has no effect in Foo.php on line 4

PHP Fatal error: Class 'Bar' not found in Foo.php on line 7

What am I doing wrong here?

UPDATE:

If instead of using namespace Acme I use namespace Acme\Bar in Bar.php, I get the same error message as shown above.


Solution

  • I've found what was going on wrong. The problem was that the UniversalClassLoader class that follows the standard PSR-0, requires that the files with the namespaces cannot be in the root directory, and must be created under a minimum of one directory.

    Here is the code in case someone wants to try the example.

    autoloader.php

    require_once __DIR__.'/vendor/Symfony/Component/ClassLoader/UniversalClassLoader.php';
    $loader = new Symfony\Component\ClassLoader\UniversalClassLoader();
    $loader->registerNamespaces(array('Acme' => __DIR__ . '/src'));
    $loader->register();
    

    ./src/Acme/Bar.php

    namespace Acme;
    
    class Bar 
    {
        // Implementation
        public static function helloWorld() {
            echo "Hello world!";
        }
    }
    

    ./src/Acme/Foo.php

    namespace Acme;
    
    require_once '../../autoloader.php';
    
    use Acme\Bar;
    
    class Foo extends Bar
    {
        // Implementation
    }
    
    $foo = new Foo();
    $foo::helloWorld();