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

前端 未结 2 1273
灰色年华
灰色年华 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

    The most realistic way to this is is by getting the endpoints of the routes.

    A controller doesn't have a required structure as the documentation implies. An action method does not need to be suffixed with Action in the name. The reason it is documented this way is because a lot of people use the catch all configuration in their routing yml, the suffix is needed to guess the endpoints.

    When you print out the routes:

    print_r($this->container->get('router')->getRouteCollection()->all());
    

    You will see the controller methods used against each route. These routes technically don't 'belong' to any bundle since you can point a route at any method of any class.

    However, you can use the list and a bit of string magic to tell the bundle based on the namespace.

    Bare in mind that a _controller like web_profiler.controller.profiler:infoAction means the method belongs to a service instantiated via dependency injection.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题