使用时Symfony 3.3
,我声明这样的服务:
class TheService implements ContainerAwareInterface
{
use ContainerAwareTrait;
...
}
在我需要 EntityManager 的每个操作中,我从容器中获取它:
$em = $this->container->get('doctrine.orm.entity_manager');
这有点烦人,所以我很好奇 Symfony 是否有类似的东西EntityManagerAwareInterface
.
传统上,您会在您的应用程序中创建一个新的服务定义services.yml
文件设置entity manager
作为构造函数的参数
app.the_service:
class: AppBundle\Services\TheService
arguments: ['@doctrine.orm.entity_manager']
最近,随着 Symfony 3.3 的发布,默认的 symfony-standard-edition 更改了默认值services.yml
文件默认使用autowire
并添加所有类AppBundle
成为服务。这消除了添加自定义服务的需要,并且在构造函数中使用类型提示将自动注入正确的服务。
您的服务类别将如下所示:
use Doctrine\ORM\EntityManagerInterface;
class TheService
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
// ...
}
有关自动定义服务依赖项的更多信息,请参阅https://symfony.com/doc/current/service_container/autowiring.html
新的默认值services.yml
配置文件可以在这里找到:https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)