0

Trying to create a service that logs information to a database. The service has to call the Doctrine\ORM\EntityManager in the constuctor, but I keep getting this error:

Catchable Fatal Error: Argument 1 passed to AppBundle\Service\EmailLoggerManager::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /Users/augustwhitlock/Desktop/symfony/SymfonyRepositories/forms/src/AppBundle/Controller/DefaultController.php on line 45 and defined

Here is what I have in my service file

namespace AppBundle\Service;

use Doctrine\ORM\EntityManager;
use AppBundle\Entity\Logger;

class EmailLoggerManager 
{

private $em;

public function __construct(EntityManager $em) 
{
    $this->em = $em;
}

public function logMessageToDatabase($type, $message, $date) 
{

    $logger = new Logger();
    $logger->setMessageType = $type;
    $logger->setMessageText = $message;
    $logger->setMessageDate = $date;

    $this->em->persist($logger);
    $this->em->flush();

}

This I how I'm handling the injection of the EntityManager.

 app.email_logger_manager:
    class: AppBundle\Services\EmailLoggerManager
    arguments: ['@doctrine.orm.entity_manager']

At this point I'm just learning about service and trying different things out. But this doesn't want to work.

Here is the edit of the DefaultController. I'm adding lines 45 and 46. There is nothing about it except the class definition.

    $emailLoggerManager = new EmailLoggerManager();
    $emailLoggerManager->logMessageToDatabase('Info', 'Hiya', new \DateTime());

    return new Response('Message Logged');

The whole concept behind the class is to just use doctrine in the service to log things to the database, clearing my controllers from having to be clogged of all that code.

Kaley36
  • 233
  • 9
  • 19
  • Hi @Kaley36, I would like to see line 45 of the following file '/Users/augustwhitlock/Desktop/symfony/SymfonyRepositories/forms/src/AppBundle/Controller/DefaultController.php'. Can you edit your question and put the line how you call your services. Thanks. – Anjana Silva May 10 '17 at 11:11

1 Answers1

0

You should call the service from the controller as follows:

$this->get('app.email_logger_manager')
    ->logMessageToDatabase('Info', 'Hiya', new \DateTime());

instead of instantiating the class directly in the controller.

Furthermore it is advisable to pass the "@doctrine" service instead of @doctrine.orm.entity_manager due to the possibility of the EntityManager being closed. The constructor would than have to receive Doctrine\Bundle\DoctrineBundle\Registry instead of Doctrine\ORM\EntityManager

Rico Humme
  • 456
  • 5
  • 12
  • Thank you so much. I did forget to do that. Thats for your answer. I think I coded too much last night. – Kaley36 May 10 '17 at 23:07