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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With