Symfony3 Hook Up Routes Annotations

I am writing my own PHP framework built on top of Symfony components as a training exercise. I followed the tutorial found at http://symfony.com/doc/current/create_framework/index.html to create my framework.

Now I would like to connect my routes to my controllers using annotations. I have the following code to configure 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();
$context->fromRequest($request);

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

// Try to get a matching route for the request
$request->attributes->add($matcher->match($request->getPathInfo()));

I came across the following class to download annotations, but I'm not sure how to use it:

https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Loader/AnnotationDirectoryLoader.php

I would appreciate it if someone could help.

thank

+4
1

, , . , autoload.php :

use Doctrine\Common\Annotations\AnnotationRegistry;

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

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

( ) :

$reader = new AnnotationReader();

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

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

AnnotatedRouteControllerLoader:

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

https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/Routing/AnnotatedRouteControllerLoader.php. , .

, .

+4

All Articles