为了账号安全,请及时绑定邮箱和手机立即绑定

如何防止在config / services.yaml中为捆绑包定义别名?

如何防止在config / services.yaml中为捆绑包定义别名?

PHP
跃然一笑 2021-05-06 14:31:34
我有一个捆绑包,例如,我希望能够将其注入到控制器中。我希望用户要做的唯一一件事就是注册捆绑软件。然后可以随意将服务注入到他们喜欢的任何地方:namespace App\Bundles;class MyService{    private $config;    public function __construct(array $options)    {        $this->config= $options;    }    public function hello()    {        echo "Hello world";    }}我试图在config / services.yaml中定义这一行:App\Bundles\MyService: '@bundle_service'这似乎可行,但是我不希望用户这样做。这是我的配置类:class Configuration implements ConfigurationInterface{    public function getConfigTreeBuilder()    {        $treeBuilder = new TreeBuilder("my_bundle");        $treeBuilder->getRootNode()            ->children()                ->arrayNode('author')                    ->children()                        ->scalarNode("name")->end()                    ->end()                ->end()            ->end();        return $treeBuilder;    }}还有my_bundle配置文件,到目前为止,这只是一个测试:my_bundle:  author:    name: "Name"我的Bundle扩展程序类:class MyBundleExtension extends Extension{    public function load(array $configs, ContainerBuilder $container)    {        $loader = new YamlFileLoader(            new FileLocator(__DIR__ .'/../Resources/config')        );        $loader->load('services.yaml');       $configuration = new Configuration();       $config = $this->processConfiguration($configuration, $configs);        $container->setDefinition('bundle_service', new Definition(MyService::class, [$config]));        $container->setAlias(MyService::class, 'bundle_service');    }}我的捆绑课程:class MyBundle extends Bundle{    public function getContainerExtension()    {        return new MyBundleExtension();    }}我想念的是什么。一切正常,除非我必须定义此行App\Bundles\MyService: '@bundle_service'中config/services.yaml,我不希望我的用户这样做。在MyBundleExtension中,我提供了正确的定义:        $container->setDefinition('bundle_service', new Definition(MyService::class, [$config]));        $container->setAlias(MyService::class, 'bundle_service');当我遗漏config/services.yaml代码时,出现此错误:Cannot autowire service "App\Bundles\MyService": argument "$options" of method "__construct()" 
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 145 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信