Answer the question
In order to leave comments, you need to log in
How to create a RouteCollection from controllers folder with annotated methods?
Good day to all!
In the process of studying and experimenting with Symfony components, the following task arose:
At the root of the project, there is a folder src/Controllers in which controllers are located. The methods in them are annotated. You need to iterate through all the controllers in the folder and subfolders, and collect the routes in the Symfony RouteCollection class.
Asking people who know to help with this issue!
PS Only the route component is used, not the whole framework
Answer the question
In order to leave comments, you need to log in
1. You need to create an AnnotationClassLoader
, whose task is to convert annotations into routes. The abstract class is in the component , you just need to define the method configureRoute
. You can take the code from the framework as a basis
namespace App\Router;
use Symfony\Component\Routing\Loader\AnnotationClassLoader as BaseLoader;
use Symfony\Component\Routing\Route;
class AnnotationClassLoader extends BaseLoader
{
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
{
if ('__invoke' === $method->getName()) {
$route->setDefault('_controller', $class->getName());
} else {
$route->setDefault('_controller', $class->getName().'::'.$method->getName());
}
}
}
use App\Router\AnnotationClassLoader;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
use Symfony\Component\Routing\Loader\AnnotationFileLoader;
use Symfony\Component\Routing\Router;
$autoloader = require_once __DIR__ . '/../vendor/autoload.php';
AnnotationRegistry::registerLoader(array($autoloader, 'loadClass'));
$reader = new AnnotationReader();
$annotationClassLoader = new AnnotationClassLoader($reader);
$fileLocator = new FileLocator([__DIR__]);
$loaderResolver = new LoaderResolver([
new AnnotationFileLoader($fileLocator, $annotationClassLoader),
new AnnotationDirectoryLoader($fileLocator, $annotationClassLoader),
]);
$loader = new DelegatingLoader($loaderResolver);
$router = new Router($loader, __DIR__ . '/../src/Controller');
dump($router->getRouteCollection());
See the source of the console command bin/console debug:router
https://symfony.com/doc/current/routing.html
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question