Symfony 4在服务中使用主义

Ale*_*sov 0 php symfony symfony4

当我在控制器内调用自定义服务时,出现此异常:

试图调用类“ App \ Service \ schemaService”的未定义方法“ getDoctrine”。

这是我的自定义服务/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();
    }

}
?>
Run Code Online (Sandbox Code Playgroud)

多数民众赞成在我的控制器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();

    }
}
?>
Run Code Online (Sandbox Code Playgroud)

在/config/services.yaml内部,添加以下行:

services:
    App\Service\schemaService:
        arguments: ["@doctrine.orm.default_entity_manager"]
Run Code Online (Sandbox Code Playgroud)

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

Dir*_*ber 6

您正在构造EntityManagerInterface(顺便说一句),但是随后使用的方法不在其中。

代替

$em = $this->getDoctrine()->getManager(); // ** Exception here ** //
Run Code Online (Sandbox Code Playgroud)

使用:

$em = $this->em;
Run Code Online (Sandbox Code Playgroud)