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

家住魔仙堡 提交于 2019-12-02 20:26:21

问题


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

Thank's


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/20610638/symfony2-a-way-to-get-all-controllers-of-a-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!