猿问

Symfony - 在捆绑包内创建自己的配置(service.yaml)

我花了很多时间尝试某件事,但也许这是不可能的。抱歉我的语言不好。因此,我按照 Symfony Doc https://symfony.com/doc/current/bundles.html创建新的 Bundle,然后按照https://symfony.com/doc/current/bundles/extension.html创建 DI扩大。

我的文件:AcmeHelloExtension.php

namespace App\Acme\HelloBundle\DependencyInjection;


use Symfony\Component\Config\FileLocator;

use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

use Symfony\Component\DependencyInjection\Extension\Extension;

use Symfony\Component\DependencyInjection\ContainerBuilder;


class AcmeHelloExtension extends Extension

{


    public function load(array $configs, ContainerBuilder $container)

    {

        $loader = new XmlFileLoader(

            $container,

            new FileLocator(__DIR__.'/../Resources/config')

        );

        $loader->load('services.xml');

    }

}

AcmeHelloBundle.php



namespace App\Acme\HelloBundle;


use Symfony\Component\HttpKernel\Bundle\Bundle;


class AcmeHelloBundle extends Bundle

{


}


我将其添加到 config/bundles.php


src/Acme/HelloBundle/Resources/config/services.yaml


services:

    App\Acme\HelloBundle\AcmeHelloBundle:

        tags: ['example-tags']

该服务文件不会自动加载,我是否需要执行后续步骤或者它应该可以工作?当我使用 debug:container ....bundle... 检查它时,选项标签具有空值。当我将此代码放入 config/services.yaml 时,它就可以工作。


慕少森
浏览 98回答 1
1回答

慕妹3242003

基本问题是捆绑包的源代码位于项目的 src 目录下:project    src        Ztest            ZtestBundle.php这反过来导致应用程序的 config/services.yaml 文件自动装配捆绑包的服务:# project\config\services    App\:        resource: '../src/'        exclude:            - '../src/DependencyInjection/'            ...            - '../src/Ztest' # Add this to fix the problem排除捆绑包的源代码解决了问题。应用程序级别的自动接线会覆盖在捆绑包级别完成的任何手动接线。当然,一般来说,如果您确实决定需要一个捆绑包,那么它的源代码应该位于它自己的独立目录中:project    src    src-ztest-bundle为此,您还需要更新composer.json 的 psr-4 部分并运行“composer dump-autoload”。请记住,在 Symfony 4+ 中,自定义捆绑包的唯一推荐用法是在多个 Symfony 应用程序之间共享代码。在这种情况下,捆绑包最终应该位于它自己的存储库和作曲家包中。但是,应用程序内部的自定义捆绑包仍然受支持,并且有时它们会很有用。
随时随地看视频慕课网APP
我要回答