【问题标题】:Choose parent/child bundle depends on domain in Symfony2选择父/子包取决于 Symfony2 中的域
【发布时间】:2012-12-28 05:43:06
【问题描述】:

假设我有两个捆绑包ParentBundleChildBundleChildBundle“扩展”ParentBundle by

// ChildBundle/ChildBundle.php
<?php

namespace ChildBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ChildBundle extends Bundle
{
    public function getParent()
    {
        return 'ParentBundle';
    }

}

然后,我将路由从ParentBundle复制到ChildBundle,并在app/config/routing.yml中指定要使用的路由,并将routing.yml重命名为Symfony2 bundle inheritance losing parent bundles routes

// app/config/routing.yml
child:
    resource: "@ChildBundle/Resources/config/routing_child.yml"
    hostname_pattern: child.example.com
    prefix:   /

parent:
    resource: "@ParentBundle/Resources/config/routing.yml"
    prefix:   /

之后,我在ChildBundle 中创建一个具有相同路径和名称的模板,以覆盖ParentBundle 中的同名模板。

但是,它会导致一直在ChildBundle 中加载模板。

所以,我的问题是,在使用 @ 987654337@ 在另一个域中(即,当用户进入 example.com 时,在 ParentBundle 中使用覆盖的模板/控制器等)?

【问题讨论】:

    标签: symfony symfony-2.2


    【解决方案1】:

    您应该阅读我所做的这个答案:Main page to sub applications on Symfony2

    实际上你必须在 web 文件夹中创建 2 个控制器,例如: web/app.php, web/app_child.php

    在app_child.php里面,调用一个新的环境,这里叫“child”:

    // ...    
    $kernel = new AppKernel('child', false);
    // ...
    

    创建一个特定于子包的 config_child.yml,您可以在此处粘贴 config.yml 内容,甚至可以导入 config.yml 以防止重复代码:

    // config_child.yml
    imports:
        - { resource: config.yml }
    

    新建一个包含子bundle的路由的路由文件,例如routing_child.yml,并在config_child.php中导入这个文件:

    framework:
        router:
            resource: "%kernel.root_dir%/config/routing_child.yml"
    

    从您的经典 routing.yml 文件中删除子捆绑路由。

    现在使用您的 web/.htaccess 根据子域调用正确的环境:

    <IfModule mod_rewrite.c>
        RewriteEngine On
    
        # Hit child app
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{HTTP_HOST} !^child\.example.com$ [NC]
        RewriteRule ^(.*)$ app_child.php [QSA,L]
    
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ app.php [QSA,L]
    </IfModule>
    

    就是这样,现在您的应用程序将根据域加载正确的路由配置;)

    【讨论】:

    • 我的同事认为它太 hacky 并转而使用扩展控制器/模板。无论如何,谢谢你的想法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2012-06-03
    • 2021-12-11
    • 1970-01-01
    • 2017-11-07
    • 2020-05-13
    • 2013-01-15
    相关资源
    最近更新 更多