[英]Symfony: set “public” property in “services.yaml” for all classes in selected directory
我希望能够通过他们的类名创建服务。 一种方法:在“services.yaml”中设置“public”属性,但我不想为我的项目中的所有类设置“public”属性
服务.yaml
services:
_defaults:
public: false # it helps to optimize performance, doesn't it?
App\Service\Service1
public: true
App\Service\Service2
public: true
App\Service\Service3
public: true
App\Service\* # why I can't use something like "*" here ???
public: true
服务1.php
namespace App\Service;
class Service1
{
// important: every service can have one or more dependencies (Foo, Bar, Baz ... etc)
public function __construct(Foo $foo, Bar $bar)
{
$this->foo = $foo;
//..........
}
}
MyController.php
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
// hier $className is any class name like "App/Service/xxxx"
public function myAction (string $className)
{
return $this->container->get($className);
}
问题:
谢谢
为什么需要将服务设置为公开? 它违反了 Symfony 最佳实践,该实践不鼓励直接从容器中获取服务。
如果您希望定义以 class 名称命名的服务,则使用以下命令引用它们就足够了:
services:
App\Service\Service1: ~
App\Service\Service2: ~
App\Service\Service3: ~
App\Service\Service4:
arguments:
- '@App\Service\Service1'
- '@App\Service\Service2'
- '@App\Service\Service3'
然后将它们直接注入您的控制器,而不是使用容器。
也许您可以利用 YAML 导入功能来概括您需要的配置,使其更易于维护。
例如:
# /config/services.yaml
imports:
- { resource: 'services/public/*.yaml' } # Import public services
- { resource: 'services/private/*.yaml' } # Import private services
尽管如前所述,强制容器服务公开违反了 Symfony 约定,并且在未来的版本中将不再支持。 使用依赖注入而不是直接与服务容器交互。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.