Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4 use Doctrine inside a Service

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?

like image 797
Aleksov Avatar asked Mar 06 '23 01:03

Aleksov


1 Answers

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;
like image 102
Dirk J. Faber Avatar answered Mar 07 '23 17:03

Dirk J. Faber