When i call my custom service inside my controller i get this exception:
Attempted to call an undefined method named "getDoctrine" of class "App\\Service\\schemaService".
This is my custom service /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();
}
}
?>
Thats is my 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();
}
}
?>
Inside a /config/services.yaml i add this lines:
services:
App\Service\schemaService:
arguments: ["@doctrine.orm.default_entity_manager"]
How i can use Doctrine inside a Services? What i do wrong?
You are constructing the EntityManagerInterface (which is fine btw), but then you use methods that are not in it.
Instead of
$em = $this->getDoctrine()->getManager(); // ** Exception here ** //
Use:
$em = $this->em;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.