【问题标题】:Cannot autoload routing from Bundles无法从捆绑包中自动加载路由
【发布时间】:2014-08-03 15:13:50
【问题描述】:

我在从捆绑包中自动加载路由时遇到问题。我在文件夹中有 routing.yml 文件:Bundle\UsersBundle\Resources\config。我正在加载他们在 Symfony 食谱中所说的路线(http://symfony.com/doc/current/cookbook/routing/custom_route_loader.html)。这一切都适用于一个捆绑包,但是当我将另一个捆绑包添加到 AppKernel 时,它不会加载新的路由。看起来每个包都需要在 main routing.yml 中单独输入(这正是我不想拥有的)。每个 RoutesLoader 服务都设置了正确的标签,并且容器正在正确加载此服务。

routing.yml:(此配置有效,但它需要来自另一个捆绑包的 RouteLoader 必须返回另一种类型 - “bundle_routes_2” - 当它返回“bundle_routes”时,不会加载路由)

bundles_routes:
    resource: .
    type: bundle_routes

bundles_routes_2:
    resource: .
    type: bundle_routes_2

更具体地说——例如我有 3 个捆绑包——UsersBundle、PermissionsBundle 和 GroupsBundle。每个包在其资源文件夹(bundle_folder/Resources/config/routing.yml)中都有路由。每个包都有 RoutesLoader 类,看起来像这样:

<?php

namespace Acme\UsersBundle\Routing;

use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;

class UsersRoutesLoader extends Loader
{
    public function load($resource, $type = null)
    {
        $collection = new RouteCollection();
        $resource = "@AcmeUsersBundle/Resources/config/routing.yml";
        $type = "yaml";
        $importedRoutes = $this->import($resource, $type);
        $collection->addCollection($importedRoutes);
        return $collection;
    }

    public function supports($resource, $type = null)
    {
        return $type === "bundle_routes";
    }
}

主路由文件看起来像这样:

acme_bundles_routes:
    resource: .
    type: bundle_routes

但它仅适用于一个捆绑包。我必须将 routing.yml 更改为:

acme_bundles_routes:
        resource: .
        type: bundle_routes
acme_bundles_routes_2:
        resource: .
        type: bundle_routes_2
acme_bundles_routes_3:
        resource: .
        type: bundle_routes_3

每个 RoutesLoader 都必须返回对应的类型。

【问题讨论】:

    标签: php symfony routing bundle autoload


    【解决方案1】:

    为什么需要自定义加载器?

    http://symfony.com/doc/current/book/routing.html#routing-include-external-resources

    您的父母routing.yml 应包含:

    AcmeBundle:
        resource: "@AcmeBundle/Resources/config/routing.yml"
    

    既然你想拥有各种路由文件,那么你可以拥有(routing.yml):

    admin_routes:
        resource: "@AcmeBundle/Resource/config/routes/admin.yml"
    user_routes:
        resource: "@AcmeBundle/Resource/config/routes/user.yml"
    

    等等等等。在任何这些捆绑 yml 文件中,您都将包含路径定义。

    【讨论】:

    • 但是在我的应用程序中,捆绑包将根据用户权限动态加载,这就是为什么我不想在主路由中声明每条路由,而只有捆绑包会加载其路由。
    • 您制造的并发症超出了要求。使用默认的自动加载器并根据角色允许路由的性能同样不会差。因为这不仅仅是您需要担心的路由。 AppKerenl.php 中的服务和定义呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 2016-12-17
    • 2011-11-07
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多