Symfony 4 在服务中使用 Doctrine

Symfony 4 use Doctrine inside a Service

当我在我的控制器中调用我的自定义服务时,我得到了这个异常:

试图调用 class "App\Service\schemaService" 的名为 "getDoctrine" 的未定义方法 "App\Service\schemaService"。

这是我的定制服务/src/Service/schemaService。php

<?php

namespace App\Service;

use App\Entity\SchemaId;
use Doctrine\ORM\EntityManagerInterface;

class schemaService {

    private $em;

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

    public function createSchema($schema){

        $em = $this->getDoctrine()->getManager(); // ** Exception here ** //

        $schemaid=new SchemaId();
        $schemaid->setSId(1);
        $schemaid->setSName('test');
        $schemaid->setSType(1);

        $em->persist($schemaid);
        $em->flush();
        return $schemaid->getId();
    }

}
?>

那是我的控制器src/Controller/Controller。php

<?php

namespace App\Controller;

use App\Service\schemaService;

use Doctrine\ORM\EntityManagerInterface;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class Controller extends AbstractController {

    public function form(){

        $em = $this->getDoctrine()->getManager();
        $schemaid=new schemaService($em);
        $schemaid->createSchema(1);
        return new Response();

    }
}
?>

在 /config/services.yaml 中添加以下行:

services:
    App\Service\schemaService:
        arguments: ["@doctrine.orm.default_entity_manager"]

如何在服务中使用 Doctrine?我做错了什么?

您正在构造 EntityManagerInterface(顺便说一句,这很好),但是您使用了其中没有的方法。

而不是

$em = $this->getDoctrine()->getManager(); // ** Exception here ** //

使用:

$em = $this->em;