【问题标题】:Symfony custom route loader : import errorSymfony 自定义路由加载器:导入错误
【发布时间】:2026-02-16 10:15:02
【问题描述】:

我正在尝试根据我的数据库中的值从不同的捆绑包中动态加载 yml 路由文件。我已经按照cookbook 创建了一个自定义路由加载器,但是在导入文件时出现错误。我正在开发 Symfony 2.3。当我在 routing.yml 文件中手动添加集合时,我的路由工作正常。

我创建了一个服务来加载资源:

class ExtraLoader implements LoaderInterface
{
    private $loaded = false;

    public function load($resource, $type = null)
    {
        if (true === $this->loaded) {
            throw new \RuntimeException('Do not add the "extra" loader twice');
        }

        $loader = new AdvancedLoader($this->getResolver());
        $routes = new RouteCollection();

        $route = $loader->import('@ERPExsecBBundle/Resources/config/routing.yml');
        $route->addPrefix('/Production/');
        $routes->addCollection($route);

        $this->loaded = true;

        return $routes;
    }

    [...]
}

以及食谱中描述的高级加载器:

class AdvancedLoader extends Loader
{
    public function __construct($resolver) {
        $this->resolver = $resolver;
    }

    public function load($resource, $type = null)
    {
        $collection = new RouteCollection();
        $type = 'yaml';
        $importedRoutes = $this->import($resource, $type);
        $collection->addCollection($importedRoutes);
        return $importedRoutes;
    }

    public function supports($resource, $type = null)
    {
        return $type === 'advanced_extra';
    }
}

但我遇到了一个错误:

致命错误:未捕获的异常 'Symfony\Component\Config\Exception\FileLoaderLoadException' 带有消息“无法加载资源“@ERPExsecBBundle/Resources/config/routing.yml”。确保“ERPExsecBBundle/Resources/config/routing.yml”包已正确注册并加载到应用程序内核类中。在第 77 行的 C:\Program Files\wamp\www\alimerp\vendor\symfony\symfony\src\Symfony\Component\Config\Loader\Loader.php 中

为什么会出现这个错误?

【问题讨论】:

    标签: symfony routing


    【解决方案1】:

    在食谱中他们说:

    # app/config/routing.yml
    AcmeDemoBundle_Extra:
        resource: .
        type: extra
    

    其中“类型”应与您的 AdvancedLoader 的类型相匹配

     public function supports($resource, $type = null)
     {
         return $type === 'advanced_extra';
     }
    

    您应该尝试在 app/config/routing.yml 中将“extra”替换为“advanced_extra”

    【讨论】:

      【解决方案2】:

      您是否在 AppKernel.php 中注册了捆绑包 ERPExsecBBundle ?

      【讨论】:

      • 是的,实际上,当我在 routing.yml 文件中手动添加路由时,我的路由工作正常,但是一旦通过我的服务注册,我就会得到错误。我认为AdvancedLoader的实现可能有问题。