Reputation: 893
I created an event like this:
service.yml
AccountManager:
class: %AccountManager.class%
tags:
- { name: doctrine.event_listener, event: postPersist }
my Subscriber
class AccountManager implements EventSubscriber
{
public function getSubscribedEvents()
{
return array(
'postPersist',
'postUpdate',
);
}
public function postUpdate(LifecycleEventArgs $args)
{
$this->index($args);
}
public function postPersist(LifecycleEventArgs $args)
{
$this->index($args);
}
public function index(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager(); //BREAKPOINT
if ($entity instanceof User) {
echo $entity;
}
}
}
If i see my code where i added breakpoint, $entityManager = $args->getEntityManager();
i don't find new user in my Database. After all I Have the new user in Database.
From documentation doctrine, i can read
postPersist - The postPersist event occurs for an entity after the entity has been made persistent. It will be invoked after the database insert operations. Generated primary key values are available in the postPersist event.
My questions are
Upvotes: 2
Views: 483
Reputation: 44396
Why I don't have new user in my Database during my Event?
That's because DB transaction isn't commited at that time. If you take a look at a hearth of Doctrine, UnitOfWork::commit()
function you'll see that in your case following operations are performed:
preFlush
event.onFlush
event.Call executeInserts()
INSERT
s.postPersist
event.Commit the transaction. That's the moment when your data becamse visible to others (transactions) in RDBMS.
postFlush
event.I don't understand the main difference between Listener/Subscriber. In this case,what is the better?
They are pretty much two different ways to achieve exactly the same. In case of EventListeners you configure them from the outside world, pseudocode:
$ed = new EventDispatcher();
$ed->addListener('some.event', $myObject, 'myMethod'); // $myObject::myMethod listens
// to some.event
$ed->addSubscriber($myObject); // ask $myObject for events it wants to listen to
// EventDispatcher::addSubscriber could look like this
function addSubscriber(EventSubscriber $object) {
foreach ($object->getSubscribedEvents() as $event => $method) {
$this->addListener($event, $object, $method);
}
}
I would say that both of them are equal in terms of "which one is better" in this case.
Upvotes: 3