gpt4 book ai didi

php - Symfony 4 在服务中使用 Doctrine

转载 作者:行者123 更新时间:2023-12-04 00:29:39 26 4
gpt4 key购买 nike

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

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

}
?>

那是我的 Controller 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;

关于php - Symfony 4 在服务中使用 Doctrine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com