Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony class loader - usage? no examples of actual usage

Tags:

php

symfony

I've been playing a bit with the Symfony class loader (read about others, the concept and started implementing).

I've read http://symfony.com/doc/current/components/class_loader.html as well I've changed the directories structure to fit and all. Here's a small source-code which fails:

Filename: test.php , dir: C:/test/BE/src/main.php

   <?php
    define('BASE_DIR','/../..');

    echo BASE_DIR.'/BE/libs/symphony/component/ClassLoader/2.1.0/UniversalClassLoader.php';
    require_once BASE_DIR.'/BE/libs/symphony/component/ClassLoader/2.1.0/UniversalClassLoader.php';

    use Symfony\Component\ClassLoader\UniversalClassLoader;

    $loader = new UniversalClassLoader();
    $loader->registerNamespace('App\Location\Location', 'Location/Location');

     // You can search the include_path as a last resort.
    $loader->useIncludePath(true);    
    $loader->register();
    use App\Location\Location;
    new App\Location\Location(); //Fatal error: Class 'App\Location\Location' not found in C:/test/BE/src/main.php

file name: Location.php , dir: C:/test/BE/src/Location/Location.php

namespace App\Location;

class Location{
    private $lat;
    private $lng;
}
like image 403
user1271518 Avatar asked Dec 12 '22 03:12

user1271518


1 Answers

By registering your namespace as follows:

$loader->registerNamespace('App\Location\Location', 'Location/Location');

autoloader will look for the App\Location\Location class in the Location/Location/App/Location/Location.php file. Note that file/directory names are case sensitive.

First parameter of registerNamespace() is either a namespace or part of the namespace. Second parameter is a path to a PSR-0 compliant library. That means that directory structure inside that path should follow PSR-0 standard. This path is not used when calculating path for given namespace.

If you want to keep your current directory structure following code should work for you:

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

I'd rather put your source code in one common directory, for example src:

src/
  App/
    Location/
        Location.php

And then register namespaces as follows:

$loader->registerNamespace('App', 'src');

By doing that you're simply telling an autoloader that it should look for App namespaced classes in the src folder. Note that it will work for every class in the App namespace (following PSR-0).

Some time ago I wrote a blog post about the Symfony autoloader. You might find it helpful: Autoloading classes in an any PHP project with Symfony2 ClassLoader component

Since you plan to use Pimple and some of the Symfony components take a look at Silex microframework. Might be it's something you need to implement.

like image 121
Jakub Zalas Avatar answered Dec 17 '22 05:12

Jakub Zalas