Correct, I think you should create your own Event Listener and event for
your sign up code. Here's something that should work:
<?php
class EmailSubscriber implements \Doctrine\Common\EventSubscriber
{
private $emailLib;
public function __construct($emailLib)
{
$this->emailLib = $emailLib;
}
/**
*
* @return array An array of method names to execute when their events
are
* dispatched
*/
public function getSubscribedEvents()
{
return array('userRegistered');
}
public function userRegistered(UserRegistrationEvent $event)
{
$this->emailLib->send([
'to' => $event->getUser()->getEmail(),
'from' => '[email protected]',
'subject' => 'Welcome to MySite.com',
'body' => 'Welcome'
]);
}
}
class UserRegistrationEvent
{
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
}
// This should be done in a ServiceProvider. Your signup code has
// to have access to this instance of EventManager.
$evm = new EventManager(); // Instance of Doctrine's Event Manager
$evm->addEventSubscriber(new EmailSubscriber());
// The following would be in your signup code:
$user = new User();
// other domain logic
$this->dm->persist($user);
$this->dm->flush($user);
$this->evm->dispatch('userRegistered', new UserRegistrationEvent($user));
In the above example, after I have saved my user I dispatch them a welcome
email. I created a "EmailSubscriber" because I may want to add more events
that dispatch emails. One example would be adding a "updateEmail"
method/event to EmailSubscriber that would be triggered when a user changes
their email address. The updateEmail method would dispatch an email with a
confirmation link. If you wanted to send a text message on registration,
I'd create a new EventSubscriber called TextMessageSubscriber, that would
look very similar to EmailSubscriber but would send a text message.
I'd once again recommend not using Doctrine's EventManager for domain
events. You should use the EventManager provided by your framework and if
it doesn't have one use Symfony's.
On Sunday, January 4, 2015 12:43:39 PM UTC-8, Parsifal wrote:
>
>
> How to create a custom event and invoke it when necessary, I looked at
> docs
> http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#the-event-system
> and if I understood it correctly, I think you mean I should create a class
> and use something like below only on my signup code? right?
> $evm->dispatchEvent(SomeEvent::SomethingToDo);
>
>
>
--
You received this message because you are subscribed to the Google Groups
"doctrine-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/doctrine-user.
For more options, visit https://groups.google.com/d/optout.