How do you register a namespace with Silex autoloader
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( Appl开发者_JS百科ication $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.
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.
I'd use
$app['autoloader']->registerNamespace('MyNamespace', __DIR__.'/../lib');
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"
}
}
}
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/',
// ...
));
Both adding appropriate statement to the autoload
section of composer.json
and registering namespaces directly calling registerNamespace
was not working for me, until I executed composer update
in the projects folder.
精彩评论