我创建了一个 bundle ,我想对其使用最佳实践。
所以我所有的服务都是私有(private)的
https://symfony.com/doc/current/service_container/alias_private.html
So unless you specifically need to access a service directly from the container via $container->get(), the best-practice is to make your services private. In fact, the default services.yaml configuration configures all services to be private by default.
还有
https://symfony.com/blog/new-in-symfony-3-4-services-are-private-by-default
In Symfony core we've already done that and we made all services and aliases private, except a few selected ones, that are required at bootstrap time. In fact, bootstrapping is the last and only legitimate use case for using the container directly.
So, should we deprecate the possibility to inject the service_container entirely alongside with ContainerAware*? That's a possibility that the community might consider when preparing Symfony 5.
我有一个必须由应用程序/ Controller 使用的特征或抽象 Controller 。该特征可以通过 Autowiring 调用私有(private)服务,并且问题已修复,但是 Symfony 的最佳实践是不要在 Bundle 中仅使用 Autowiring :
https://symfony.com/doc/current/service_container/autowiring.html
Public and Reusable Bundles¶
Public bundles should explicitly configure their services and not rely on autowiring.
那么如何在我的 Trait 或抽象 Controller 中注入(inject)我的私有(private)服务。或者甚至在应用程序 Controller 中,用户无需配置 services.yml。
我希望我说得清楚。
抱歉我的英语不好。我尝试改进它;-)
最佳答案
如果您正在开发第三方 bundle (即将由其他人使用的 bundle ),那么您必须手动定义您的服务,并且也在 xml 中定义。这些是最佳实践。
现在,第三方 bundle 可以提供公共(public)服务。您引用的文章涉及您的 AppBundle 服务,该服务应该是私有(private)的,因为包含您的应用程序/业务逻辑。默认情况下它们是私有(private)的,因为您应该使用构造函数依赖注入(inject)来使用它们,这样更容易测试。
现在,关于您的问题,您不应该在第三方 bundle 中创建 Controller :这不是一个好的做法。相反,使用路由来路由到将执行您需要的操作的服务。 Api 平台就是这样做的,在这里:
关于php - Symfony:如何在 Bundle Controller 中调用私有(private)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49988904/