Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you register a namespace with Silex autoloader

Tags:

php

symfony

silex

I'm experimenting with creating an extension with the Silex php micro framework for user authentication but I can't seem to get the autoloader to work. Can anyone shed any light?

I have a directory structure like this (truncated)

usertest
|_lib
| |_silex.phar
| |_MyNamespace
|   |_UserExtension.php
|   |_User.php
|_www
  |_index.php

The pertinent bits of index.php, which serves as the bootstrap and the front controller look like this:

require '../lib/silex.phar';

use Silex\Application;
use MyNamespace\UserExtension;

$app = new Application();
$app['autoloader']->registerNamespace( 'MyNamespace', '../lib' );
$app->register( new UserExtension() );

The class I'm trying to load looks similar this:

namespace MyNamespace;

use Silex\Application;
use Silex\ExtensionInterface;

class UserExtension implements ExtensionInterface {
    public function register( Application $app ) {
        $app['user'] = $app->share( function() use( $app ) {
            return new User();
        });
    }
}

All pretty straight forward except it throws this error:

Fatal error: Class 'MyNamespace\UserExtension' not found in /home/meouw/Projects/php/usertest/www/index.php on line 8

I have dabbled with symfony2 and have successfully followed the instructions for setting up the universal class loader, but in this instance I am stumped. Am I missing something? Any help would be appreciated.

like image 436
meouw Avatar asked May 30 '11 23:05

meouw


2 Answers

In recent versions of Silex the autoloader is deprecated and you should register all your namespaces through the composer.json file which imo is a nicer solution because you are centralizing your autoloading definitions.

Example:

{
    "require": {
        "silex/silex": "1.0.*@dev"
    },
    "autoload": {
        "psr-0": {
            "MyNameSpace": "src/"
        }
    }
}

In fact when you try to access the autoloader in any recent version of Silex the following RuntimeException is thrown:

You tried to access the autoloader service. The autoloader has been removed from Silex. It is recommended that you use Composer to manage your dependencies and handle your autoloading. See http://getcomposer.org for more information.

like image 94
ChrisR Avatar answered Sep 20 '22 07:09

ChrisR


Deprecated - As of 2014-10-21 PSR-0 has been marked as deprecated.
PSR-4 is now recommended as an alternative

That is why you should use PSR-4 syntax in composer.json

{
  "require": {
      "silex/silex": "1.0.*@dev",
  },
  "autoload": {
      "psr-4": {
          "Vendor\\Namespace\\": "/path"
      }
  }
}
like image 22
Robert Avatar answered Sep 20 '22 07:09

Robert