Question

My application file:

<?php // /src/app.php

require_once __DIR__ . '/../lib/vendor/Sensio/silex.phar';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Foo\Bar;

$app = new Silex\Application(); 
$app['autoloader']->registerNamespace('Foo', __DIR__);
$bar = new Bar();
(...)

My Bar class:

<?php /src/Bar.php

namespace Foo;

use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
use Symfony\Component\HttpFoundation\Response;

class Bar implements ControllerProviderInterface { ... }

When I do a $bar = new Bar() in my app.php, I get an error: Fatal error: Class 'Moken\Classname' not found in (...)/src/app.php on line 11

Can anyone tell me what I am doing wrong?

Was it helpful?

Solution

If you use namespace Foo; you must locate this class in Foo directory
Every namespace part is a directory in symfony

If not works, you must show the loader where to find this class In symfony2 I use for this:

use Symfony\Component\ClassLoader\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
    // HERE LOCATED FRAMEWORK SPECIFIED PATHS

    // app namespaces
    'Foo' => __DIR__ . '/../src',
));

OTHER TIPS

In your main php file (index.php) you must:

  • declare the use of your Controller Provider;
  • after creation of your Application object you must register your namespace;
  • mount your Controller Provider.

For example (Example\Controllers is the namespace and XyzControllerProvider is the Controller Provider, the url is /my/example):

[...]
// declare the use of your Controller Provider
use Example\Controllers\XyzControllerProvider;
[...]
//after creation of your Application object you must register your namespace;
$app = Application();
$app['autoloader']->registerNamespace('Example', __DIR__.'/src');
[...]
//mount your Controller Provider
$app->mount('/my/example', new Example\Controllers\XyzControllerProvider());

the Controller Provider (under src/example/controllers) will be:

<?php
namespace Example\Controllers;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
class XyzControllerProvider implements ControllerProviderInterface {
  public function connect(Application $app) {
    $controllers = new ControllerCollection();
    $controllers->get('/', function (Application $app) {
      return "DONE;"
    });
    return $controllers;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top