John Davidson

php - Cannot inject EntityManagerInterface to use doctrine inside a service on symfony3.4

0 comments
Message:


I added the EntityManagerInterface to use doctrine inside the service


namespace AppBundle\Service;

class UploadFileService
{

private $upload_directory;

private $is_api;
private $em;

public function __construct($upload_directory, EntityManagerInterface $em,$isApi = false )
{
$this->upload_directory = $upload_directory;
$this->is_api = $isApi;
$this->em = $em;
}
}

and its calles this way


$uploadService = new UploadFileService($this->getParameter('upload_directory'));

but I get this error


Type error: Too few arguments to function AppBundle\Service\UploadFileService::__construct(), 1 passed in /var/www/project/src/AppBundle/Controller/ManageController.php on line 516 and at least 2 expected

Autowiring is activated and I checked some answers here and I applied the solution but it doesn't work



My Answer:
upload_directory = $upload_directory; $this->is_api = $isApi; $this->em = $em; } public function saveFile($file) { // logic to save file using doctrine $this->em->persist($file); $this->em->flush(); }}?>

In the above code, I have added EntityManagerInterface as a type-hint in the constructor of the UploadFileService class. This allows Symfony's dependency injection container to inject an instance of EntityManagerInterface when creating an instance of UploadFileService.

Make sure you have imported the EntityManagerInterface class at the top of your file:

use Doctrine\ORM\EntityManagerInterface;

Also, make sure that you have properly configured your services.yml or services.xml file to define the service and inject the EntityManagerInterface. Here is an example of how you can define the service in services.yml:

services:
app.upload_file_service:
class: AppBundle\Service\UploadFileService
arguments:
$upload_directory: '%upload_directory%'
$em: '@doctrine.orm.entity_manager'
$isApi: false

In this configuration, we are injecting the EntityManagerInterface service provided by Doctrine into the UploadFileService class.

After making these changes, you should be able to use Doctrine's EntityManager inside your service.

Rate this post

5 of 5 based on 4239 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us