Using Symfony’s Routing component with annotations in your custom app

This was a bit of a pain to get going originally, but once it’s up, it works great!

I used composer which generated the autoload.php file used at the top, and from there I used Symfony2’s ClassLoader for autoloading my own annotation classes & other classes which are being scanned & reflected.

Code below;

<?

require_once( "vendor/autoload.php" );

use Doctrine\Common\Annotations\AnnotationRegistry;
 use Doctrine\Common\Annotations\FileCacheReader;
 use Doctrine\Common\Annotations\AnnotationReader;
 use Symfony\Component\Config\FileLocator;
 use Symfony\Component\Routing\Loader\AnnotationClassLoader;
 use Symfony\Component\Routing\Route;
 use Symfony\Component\ClassLoader\UniversalClassLoader;

// ------------------------------------------------------------------------------

class MyAnnotationClassLoader extends AnnotationClassLoader {

protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
 {
 // TODO: Implement configureRoute() method.
 echo 'configure route here' . "\n";
 }
 }

$loader = new UniversalClassLoader();
 $loader->registerNamespace('Symfony', __DIR__.'/vendor/symfony/routing');
 $loader->registerNamespace('Entities', __DIR__.'/controllers');
 $loader->register();

AnnotationRegistry::registerLoader(array($loader, "loadClass"));

// ------------------------------------------------------------------------------

$reader = new FileCacheReader(
 new AnnotationReader(),
 __DIR__ . "/cache",
 $debug = true
 );

$locator = new FileLocator();
 $annotationLoader = new MyAnnotationClassLoader($reader);

$dirLoader = new \Symfony\Component\Routing\Loader\AnnotationDirectoryLoader($locator, $annotationLoader);
 $routes = $dirLoader->load(__DIR__ . '/controllers');

print_r($routes);

Basically you need to make sure your classes are saved as per http://symfony.com/PSR0, and then you can start going ahead and using the @Route(…) annotation as needed.

See;

Leave a Reply