Silex自定义类结构和加载

I'm building an app using Silex (the micro-framework).

As my app are growing in size and the need of using the same code in several routes rises, I want to organise everything a little more..

My idea is to create some custom classes, and then share them with my app:

$app['test'] = $app->share(function () {
    require_once('../vendor/acme/src/test.php');
    $testClass = new Test();
    return new $testClass;
});

This actually works, but I need help with the following:

  1. Autoload the class with composer (the way its supposed to be done in Silex).
  2. Be able to use the existing Doctrine DBAL connection and methods within my class.

I hope someone can give me some tips how to get on, because I'm not finding the Silex docs very useful and I'm a beginner with both Silex and Composer.

Check the composer docs about autoloading, and when you added your config you should run composer dump-autoload to regenerate the composer autoloader. Then your require_once should not be necessary anymore.

Most likely this will work (assuming class Test is in src/Test.php):

{
    "autoload": {
        "psr-0": {
            "": "src/"
        }
    }
}

This will make any PSR-0 compliant class inside src/ autoloadable.

Regarding your second point (using DBAL in your class), you should configure your class as a silex service that accesses the db service. Read up on services at http://silex.sensiolabs.org/doc/services.html