Symfony 4中如何在服务中使用Doctrine

4

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

尝试调用类“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();
    }

}
?>

这是我的控制器 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来获取$this->em,为什么需要在createSchema()中再获取另一个版本的$em呢? - Alister Bulman
我并不完全理解它是如何工作的,这只是数百次尝试之一,也许我做错了什么。 - Aleksov
1个回答

7
你正在构建EntityManagerInterface(这是很好的),但是你使用了其中没有的方法。
改为:
$em = $this->getDoctrine()->getManager(); // ** Exception here ** //

使用:

$em = $this->em;

1
太好了,它帮助了我!谢谢! - Aleksov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接