Alex Rivera | Logout

How do you register a namespace with Silex autoloader

Asked 2011-05-30T23:22:58.440
13

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.

Edit
Report

2 Answers

11

I'd use

$app['autoloader']->registerNamespace('MyNamespace', __DIR__.'/../lib');
answered 2011-09-29T14:20:26.433
3

To register namespaces, just call registerNamespaces() like this:

$app = new Silex\Application();

$app['autoloader']->registerNamespaces(array(
    'Symfony'          => __DIR__.'/../vendor/',
    'Panda'            => __DIR__.'/../vendor/SilexDiscountServiceProvider/src',
    'Knp'              => __DIR__.'/../vendor/KnpSilexExtensions/',
    // ...
));
answered 2012-04-06T04:31:42.157

Your Answer