Reputation: 4679
I'm learning Symfony and I'm trying to create: a new service and Event
My service send emails
config.yml
parameters:
MyService.class: Acme\UserBundle\Services\sendEmail
MyService.transport: sendmail
service.yml
services:
MyService:
class: %MyService.class%
arguments: [@mailer]
sendEmail.php
class sendEmail {
private $mail;
public function __construct ($mail) {
$this->mail = $mail;
}
public function sendMail () {
$msg = \Swift_Message::newInstance()
->setSubject('Hi')
->setFrom('[email protected]')
->setTo('[email protected]')
->setBody('ok');
$this->mail->send($msg);
}
}
My Event
I have created these class
UserEvent.php
<?php
namespace Acme\UserBundle\Event;
final class UserEvents {
const NEW_USER='new.user';
}
newUserEvent.php
<?php
/**
* EVENT DISPATCHER
*/
namespace Acme\UserBundle\Event;
use Acme\UserBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;
class NewUserEvent extends Event {
protected $user;
public function __construct (User $user) {
$this->user = $user;
}
public function getUser () {
return $this->user;
}
}
newUserListener.php
<?php
namespace Acme\UserBundle\Event;
use Acme\UserBundle\Services\sendEmail;
class NewUserListener {
public function sendEmailToUsers(NewUserEvent $event,sendEmail $service)
{
// ... send email to users
}
}
in my controller
$em = $this->getEm();
$dispatcher = new EventDispatcher();
// attach listener
$listner = new NewUserListener();
$dispatcher->addListener(UserEvents::NEW_USER,array($listner,'sendEmailToUsers'));
$user = $em->getRepository('AcmeUserBundle:User')->findOneBy(array('username' => 'alex')); //mock
$event = new NewUserEvent($user,$this->get('MyService'));
$dispatcher->dispatch(UserEvents::NEW_USER,$event);
return new Response('hi');
I'd like to use my service inside my event by I have this error
ContextErrorException: Catchable Fatal Error: Argument 2 passed to Acme\UserBundle\Event\NewUserListener::sendEmailToUsers() must be an instance of Acme\UserBundle\Services\sendEmail, none given in Acme/UserBundle/Event/NewUserListener.php
Upvotes: 0
Views: 189
Reputation: 20185
There are many points here :
http://symfony.com/doc/current/cookbook/service_container/event_listener.html
$disptacher = $this->container->get('event_dispatcher');
Upvotes: 1