当我在控制器中调用自定义服务时,出现以下异常:
尝试调用类“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?我做错了什么?
$this->em
,为什么需要在createSchema()
中再获取另一个版本的$em
呢? - Alister Bulman