I have created custom event like when user is generataed then Event dispatcher will fire that event.
I am following this tutorial. I want to know that in his class CommentListener how can I access the entity manager because I want to persist few things in the database.
The class is like this:
class CommentListener
{
protected $mailer;
public function __construct(Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function onCommentEvent(CommentEvent $event)
{
$post = $event->getPost();
$comment = $event->getComment();
foreach ($post->getSubscribers() as $subscriber) {
$message = Swift_Message::newInstance()
->setSubject('New comment posted on ' . $post->getTitle())
->setFrom('send@example.com')
->setTo($subscriber->getEmail())
->setBody("Hey, somebody left a new comment on a post you're subscribed to! It says: " . $comment->getBody())
;
$this->mailer->send($message);
}
}
}
So how can I access entity manager inside onCommentEvent?
Listeners are normal services. You can just inject it into constructor along with
mailer. Something along these lines:Service:
Listener class:
If you ever need to find out name of certain service run
php app/console container:debug.