我有一个捆绑包,例如,我希望能够将其注入控制器中。我希望用户要做的唯一一件事就是注册捆绑软件。然后免费将服务注入他们喜欢的任何地方:
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()"
答案 0 :(得分:1)
使用变量创建服务
services:
# ...
App\Updates\SiteUpdateManager:
arguments:
$adminEmail: '%admin_email%'
或
通过
构建服务use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class MessageGenerator
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function someMethod()
{
$parameterValue = $this->params->get('my_bundle.author.name');
// ...
}
}
答案 1 :(得分:0)
class MyBundleExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$container->setParameter('my_bundle.author.name', $config['author']['name']);
}
}
下一步
在config / services.yaml中声明服务
my_bundle.my_service.service:
class: App\Bundles\MyService
public: true
arguments:
- '%my_bundle.author.name%'