【问题标题】:Load routes if bundle is loaded如果加载了捆绑包,则加载路由
【发布时间】:2026-01-14 21:15:01
【问题描述】:

我有一个 API 包,只有在我位于子域时才加载,这是我的 AppKernel 中的内容:

if ($_SERVER['HTTP_HOST'] == 'api.mywebsite.fr')
{
    $bundles[] = new TV\ApiBundle\TVApiBundle();
}

现在我需要在我的包中的某个地方加载它自己的路由,无需使用我的包配置修改app/config/routing.yml 文件。我尝试使用此处解释的自定义路由器加载程序http://symfony.com/doc/current/cookbook/routing/custom_route_loader.html,但问题是教程的那一部分:

AcmeDemoBundle_Extra:
    resource: .
    type: extra

有没有办法避免这种配置? 我希望我的包是独立的,并且无需修改 app/config/ 中的文件即可完成所有工作。(AppKernel 部分除外:p)

问候,

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    您检查过文档的最后一部分吗?这部分在您的自定义加载器中添加资源和类型,这样您就不必在 routing.yml 中执行此操作。 http://symfony.com/doc/current/cookbook/routing/custom_route_loader.html

    namespace Acme\DemoBundle\Routing;
    
    use Symfony\Component\Config\Loader\Loader;
    use Symfony\Component\Routing\RouteCollection;
    
    class AdvancedLoader extends Loader
    {
        public function load($resource, $type = null)
        {
            $collection = new RouteCollection();
    
            $resource = '@AcmeDemoBundle/Resources/config/import_routing.yml';
            $type = 'yaml';
    
            $importedRoutes = $this->import($resource, $type);
    
            $collection->addCollection($importedRoutes);
    
            return $collection;
        }
    
        public function supports($resource, $type = null)
        {
            return $type === 'advanced_extra';
        }
    }
    

    【讨论】: