无法使用带有Bundle语法的PhpFileLoader在Routing.php

时间:2018-05-22 09:51:46

标签: php symfony

我尝试动态加载特定命名空间中所有Bundle的所有路由。因此,我将CustomRoute Loader设置为服务,并确定要添加的路由。但是PhpFileLoader无法找到Bundle。我用$this->container->getParameter('kernel.bundles');得到了你的Bundles的名字,所以不会有拼写错误。从routing.php中加载这些硬编码的Bundle可以正常工作,但不能从服务类中运行。在routing.php里面我无法确定Bundles是否已加载,因此仅使用routing.php不是解决方案。我错过了什么?到目前为止,这是我的代码:

Routing.php

<?php


// app/config/routing.php
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

$path                    = "/Controller/";

$defaultAnnotationRoutes = [
                            'SomeDefaultBundle'];

$routes = new RouteCollection();

$routes->add('somedefaulRoute', new Route('/', array(
    '_controller' => 'SomeDefaultBundle:Welcome:page',
)));

$routes->addCollection(
    $loader->import("@FOSJsRoutingBundle/Resources/config/routing/routing.xml"
));

foreach ($defaultAnnotationRoutes as $bundleName) {


    $routingConfigPath = "@" . $bundleName . $path;

    $routes->addCollection(
    // loads routes from the given routing file stored in some bundle
        $loader->import($routingConfigPath, "annotation"));

}

$routes->addCollection(
    $loader->import('mapbender.routing_loader:load', "service"));

return $routes;

服务类:

namespace Mapbender\CoreBundle\Routing;

use Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException;
use Symfony\Component\Config\Exception\FileLoaderLoadException;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\PhpFileLoader;
use Symfony\Component\Routing\RouteCollection;

class BundleLoader
{

    protected $container;
    protected $path                    = "/Controller/";
    protected $loader;

    /**
     * BundleLoader constructor.
     *
     * @param $container
     */
    public function __construct($container)
    {

        $this->container = $container;
        $rootdir = $this->container->get('kernel')->getRootDir();
        $this->loader = new PhpFileLoader(new FileLocator());

    }

    /**
     * @param      $resource
     * @param null $type
     * @return RouteCollection
     */
    public function load($resource, $type = null)
    {
        $routes  = new RouteCollection();
        $bundles = $this->container->getParameter('kernel.bundles');
        foreach ($bundles as $bundleName => $bundlePath) {

            if (preg_match('/CompanyVendor/', $bundleName, $matches)) {

                $routingConfigPath = "@" . $bundleName.  $this->path;

                try {
                    $routes->addCollection(
                        $this->loader->import($routingConfigPath)
                    );
                } catch (FileLoaderImportCircularReferenceException $e) {
                    throw $e;
                } catch (FileLoaderLoadException $e) {
                    throw $e;
                }
            }
        }

        return $routes;
    }


}

0 个答案:

没有答案