当我在控制器内调用自定义服务时,出现此异常:
试图调用类别为“ 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?我做错了什么?
答案 0 :(得分:4)
您正在构造EntityManagerInterface(顺便说一句),但是随后使用的方法不在其中。
代替
$em = $this->getDoctrine()->getManager(); // ** Exception here ** //
使用:
$em = $this->em;