Symfony2 - A way to get all controllers of a bundle?

前端 未结 2 1302
灰色年华
灰色年华 2021-01-26 18:36

Is there a way to get all controllers (and the class) of a bundle ? Including all parent contollers ?

Thank\'s

2条回答
  •  天命终不由人
    2021-01-26 19:04

    Altough there is no offical way to get the controllers, you can use the following code to get all controllers:

    $bundles = $this->container->getParameter('kernel.bundles');
    $controllers = [];
    foreach ($bundles as $bundle) {
        $reflection = new \ReflectionClass($bundle);
        $controllerDirectory = dirname($reflection->getFileName()) . '/Controller';
        if (file_exists($controllerDirectory)) {
            $d = dir($controllerDirectory);
            while (false !== ($entry = $d->read())) {
    
                if (preg_match("/^([A-Z0-9-_]+Controller).php/i", $entry, $matches)) {                        
                    $controllers[] = ['fileName' => $controllerDirectory. '/'. $entry, 'class' => $reflection->getNamespaceName() . '\Controller\\' . $matches[1]];
                }
            }
            $d->close();
        }
    }
    print_r($controllers);
    

提交回复
热议问题