如何将Doctrine Entity Manager注入到Symfony 4 Service中 [英] How to inject Doctrine Entity Manager into Symfony 4 Service

查看:42
本文介绍了如何将Doctrine Entity Manager注入到Symfony 4 Service中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器

use Doctrine\ORM\EntityManagerInterface:
class ExampleController{
   public function someFunction(ExampleService $injectedService){
       $injectedService->serviceFunction();
    }
}

有服务

use Doctrine\ORM\EntityManagerInterface;
class ExampleService{
    public function __construct(EntityManagerInterface $em){
        ...
    }    
}

但是,由于传递了0个参数(未注入EntityManagerInterface),对 someFunction()的调用失败.我正在尝试从服务中使用EntityManager.自动接线功能已开启.我已经尝试过Symfony3的解决方案,但是除非我丢失了某些东西,否则它们似乎无法工作.

However, calls to someFunction() fail due to 0 parameters being passed (the EntityManagerInterface is not being injected). I am attempting to use the EntityManager from the Service. Autowiring is on. I've tried the solutions for Symfony3 but they don't seem to work unless I'm missing something.

这是我的services.yaml:

Here is my services.yaml:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false 

    App\:
        resource: '../src/*'
        exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'

    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

推荐答案

仅在Symfony 4中使用.

Use only in Symfony 4.

use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Name; //if you use entity for example Name

class ExampleService{
    private $em;
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    function newName($code) // for example with a entity
    {
        $name = new Name();
        $name->setCode($code); // use setter for entity

        $this->em->persist($name);
        $this->em->flush();
    }
}

这篇关于如何将Doctrine Entity Manager注入到Symfony 4 Service中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆