nfplee nfplee - 1 year ago 70
PHP Question

Symfony3 Hook Up Annotation Routes

I'm writing my own PHP framework built on top of Symfony components as a learning exercise. I followed the tutorial found at to create my framework.

I'd now like to wire up my routes against my controllers using annotations. I currently have the following code to setup the routing:

// Create the route collection
$routes = new RouteCollection();

$routes->add('home', new Route('/{slug}', [
'slug' => '',
'_controller' => 'Controllers\HomeController::index',

// Create a context using the current request
$context = new RequestContext();

// Create the url matcher
$matcher = new UrlMatcher($routes, $context);

// Try to get a matching route for the request

I have come across the following class to load the annotations but I'm not sure how to use it:

I'd appreciate it if someone could help.


Answer Source

I've finally managed to get this working. First I changed where I included the autoload.php file to the following:

use Doctrine\Common\Annotations\AnnotationRegistry;

$loader = require __DIR__ . '/../vendor/autoload.php';

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

Then I changed the routes collection bit above to:

$reader = new AnnotationReader();

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

$loader = new AnnotationDirectoryLoader($locator, $annotationLoader);
$routes = $loader->load(__DIR__ . '/../Controllers'); // Path to the app's controllers

Here's the code for the AnnotatedRouteControllerLoader:

class AnnotatedRouteControllerLoader extends AnnotationClassLoader {
    protected function configureRoute(Route $route, ReflectionClass $class, ReflectionMethod $method, $annot) {
        $route->setDefault('_controller', $class->getName() . '::' . $method->getName());

This has been taken from You may wish to modify it to support additional annotations.

I hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download