Symfony EventSubscribe on Entity











up vote
0
down vote

favorite












trying to make an subscriber for Entity actions (CRUD) and cannot figure it out.



I know there is a way, where I can make listener and send him 3 different events, but that's not what I want to reach, I dont even think is good solution.



Event Subscriber



<?php

namespace AppEventListener;


use AppEntityLog;
use DoctrineORMEntityManagerInterface;
use DoctrineORMEventLifecycleEventArgs;
use DoctrineORMEvents;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;

/**
* Part of program created by David Jungman
* @author David Jungman <davidjungman.web@gmail.com>
*/
class EntitySubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $em;

/**
* @var TokenStorageInterface
*/
private $tokenStorage;

public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
{
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}

public static function getSubscribedEvents()
{
return array(
Events::postPersist,
Events::postUpdate,
Events::postRemove,
);
}

public function postUpdate(LifecycleEventArgs $args)
{
$this->logEvent($args, "remove");
}

public function postRemove(LifecycleEventArgs $args)
{
$this->logEvent($args, "remove");
}

public function postPersist(LifecycleEventArgs $args)
{
$this->logEvent($args, "create");
}

private function logEvent(LifecycleEventArgs $args, string $method)
{
$entity = $args->getEntity();
if($entity->getShortName() != "Log")
{
$user = $this->tokenStorage->getToken()->getUser();
$log = new Log();

$log
->setUser($user)
->setAffectedTable($entity->getShortName())
->setAffectedItem($entity->getId())
->setAction($method)
->setCreatedAt();

$this->em->persist($log);
$this->em->flush();
}
}
}


and my Service.yaml part



AppEventListenerEntitySubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }


I have tried:



I've looked into these 2 official tutorials:
-https://symfony.com/doc/current/event_dispatcher.html
-https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html



but neither helped.. when I use shown part of config, my computer freeze.



When I try to debug it, I can see these methods active
( php bin/console debug:event-dispatcher )



but they are listening on "event" event










share|improve this question


























    up vote
    0
    down vote

    favorite












    trying to make an subscriber for Entity actions (CRUD) and cannot figure it out.



    I know there is a way, where I can make listener and send him 3 different events, but that's not what I want to reach, I dont even think is good solution.



    Event Subscriber



    <?php

    namespace AppEventListener;


    use AppEntityLog;
    use DoctrineORMEntityManagerInterface;
    use DoctrineORMEventLifecycleEventArgs;
    use DoctrineORMEvents;
    use SymfonyComponentEventDispatcherEventSubscriberInterface;
    use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;

    /**
    * Part of program created by David Jungman
    * @author David Jungman <davidjungman.web@gmail.com>
    */
    class EntitySubscriber implements EventSubscriberInterface
    {
    /**
    * @var EntityManagerInterface
    */
    private $em;

    /**
    * @var TokenStorageInterface
    */
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
    {
    $this->em = $em;
    $this->tokenStorage = $tokenStorage;
    }

    public static function getSubscribedEvents()
    {
    return array(
    Events::postPersist,
    Events::postUpdate,
    Events::postRemove,
    );
    }

    public function postUpdate(LifecycleEventArgs $args)
    {
    $this->logEvent($args, "remove");
    }

    public function postRemove(LifecycleEventArgs $args)
    {
    $this->logEvent($args, "remove");
    }

    public function postPersist(LifecycleEventArgs $args)
    {
    $this->logEvent($args, "create");
    }

    private function logEvent(LifecycleEventArgs $args, string $method)
    {
    $entity = $args->getEntity();
    if($entity->getShortName() != "Log")
    {
    $user = $this->tokenStorage->getToken()->getUser();
    $log = new Log();

    $log
    ->setUser($user)
    ->setAffectedTable($entity->getShortName())
    ->setAffectedItem($entity->getId())
    ->setAction($method)
    ->setCreatedAt();

    $this->em->persist($log);
    $this->em->flush();
    }
    }
    }


    and my Service.yaml part



    AppEventListenerEntitySubscriber:
    tags:
    - { name: doctrine.event_subscriber, connection: default }


    I have tried:



    I've looked into these 2 official tutorials:
    -https://symfony.com/doc/current/event_dispatcher.html
    -https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html



    but neither helped.. when I use shown part of config, my computer freeze.



    When I try to debug it, I can see these methods active
    ( php bin/console debug:event-dispatcher )



    but they are listening on "event" event










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      trying to make an subscriber for Entity actions (CRUD) and cannot figure it out.



      I know there is a way, where I can make listener and send him 3 different events, but that's not what I want to reach, I dont even think is good solution.



      Event Subscriber



      <?php

      namespace AppEventListener;


      use AppEntityLog;
      use DoctrineORMEntityManagerInterface;
      use DoctrineORMEventLifecycleEventArgs;
      use DoctrineORMEvents;
      use SymfonyComponentEventDispatcherEventSubscriberInterface;
      use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;

      /**
      * Part of program created by David Jungman
      * @author David Jungman <davidjungman.web@gmail.com>
      */
      class EntitySubscriber implements EventSubscriberInterface
      {
      /**
      * @var EntityManagerInterface
      */
      private $em;

      /**
      * @var TokenStorageInterface
      */
      private $tokenStorage;

      public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
      {
      $this->em = $em;
      $this->tokenStorage = $tokenStorage;
      }

      public static function getSubscribedEvents()
      {
      return array(
      Events::postPersist,
      Events::postUpdate,
      Events::postRemove,
      );
      }

      public function postUpdate(LifecycleEventArgs $args)
      {
      $this->logEvent($args, "remove");
      }

      public function postRemove(LifecycleEventArgs $args)
      {
      $this->logEvent($args, "remove");
      }

      public function postPersist(LifecycleEventArgs $args)
      {
      $this->logEvent($args, "create");
      }

      private function logEvent(LifecycleEventArgs $args, string $method)
      {
      $entity = $args->getEntity();
      if($entity->getShortName() != "Log")
      {
      $user = $this->tokenStorage->getToken()->getUser();
      $log = new Log();

      $log
      ->setUser($user)
      ->setAffectedTable($entity->getShortName())
      ->setAffectedItem($entity->getId())
      ->setAction($method)
      ->setCreatedAt();

      $this->em->persist($log);
      $this->em->flush();
      }
      }
      }


      and my Service.yaml part



      AppEventListenerEntitySubscriber:
      tags:
      - { name: doctrine.event_subscriber, connection: default }


      I have tried:



      I've looked into these 2 official tutorials:
      -https://symfony.com/doc/current/event_dispatcher.html
      -https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html



      but neither helped.. when I use shown part of config, my computer freeze.



      When I try to debug it, I can see these methods active
      ( php bin/console debug:event-dispatcher )



      but they are listening on "event" event










      share|improve this question













      trying to make an subscriber for Entity actions (CRUD) and cannot figure it out.



      I know there is a way, where I can make listener and send him 3 different events, but that's not what I want to reach, I dont even think is good solution.



      Event Subscriber



      <?php

      namespace AppEventListener;


      use AppEntityLog;
      use DoctrineORMEntityManagerInterface;
      use DoctrineORMEventLifecycleEventArgs;
      use DoctrineORMEvents;
      use SymfonyComponentEventDispatcherEventSubscriberInterface;
      use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;

      /**
      * Part of program created by David Jungman
      * @author David Jungman <davidjungman.web@gmail.com>
      */
      class EntitySubscriber implements EventSubscriberInterface
      {
      /**
      * @var EntityManagerInterface
      */
      private $em;

      /**
      * @var TokenStorageInterface
      */
      private $tokenStorage;

      public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
      {
      $this->em = $em;
      $this->tokenStorage = $tokenStorage;
      }

      public static function getSubscribedEvents()
      {
      return array(
      Events::postPersist,
      Events::postUpdate,
      Events::postRemove,
      );
      }

      public function postUpdate(LifecycleEventArgs $args)
      {
      $this->logEvent($args, "remove");
      }

      public function postRemove(LifecycleEventArgs $args)
      {
      $this->logEvent($args, "remove");
      }

      public function postPersist(LifecycleEventArgs $args)
      {
      $this->logEvent($args, "create");
      }

      private function logEvent(LifecycleEventArgs $args, string $method)
      {
      $entity = $args->getEntity();
      if($entity->getShortName() != "Log")
      {
      $user = $this->tokenStorage->getToken()->getUser();
      $log = new Log();

      $log
      ->setUser($user)
      ->setAffectedTable($entity->getShortName())
      ->setAffectedItem($entity->getId())
      ->setAction($method)
      ->setCreatedAt();

      $this->em->persist($log);
      $this->em->flush();
      }
      }
      }


      and my Service.yaml part



      AppEventListenerEntitySubscriber:
      tags:
      - { name: doctrine.event_subscriber, connection: default }


      I have tried:



      I've looked into these 2 official tutorials:
      -https://symfony.com/doc/current/event_dispatcher.html
      -https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html



      but neither helped.. when I use shown part of config, my computer freeze.



      When I try to debug it, I can see these methods active
      ( php bin/console debug:event-dispatcher )



      but they are listening on "event" event







      php symfony symfony4






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 18 at 10:57









      David Jungman

      104




      104
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Doctrine has it's own events handler/subscriber system. However, with the class SymfonyComponentEventDispatcherEventSubscriberInterface; that you are implementing, that is from the Symfony event system.



          <?php
          use DoctrineORMEvents;
          use DoctrineCommonEventSubscriber; // **the Doctrine Event subscriber interface**
          use DoctrineCommonPersistenceEventLifecycleEventArgs;

          class MyEventSubscriber implements EventSubscriber
          {
          public function getSubscribedEvents()
          {
          return array(
          Events::postUpdate,
          );
          }

          public function postUpdate(LifecycleEventArgs $args)
          {
          $entity = $args->getObject();
          $entityManager = $args->getObjectManager();

          // perhaps you only want to act on some "Product" entity
          if ($entity instanceof Product) {
          // do something with the Product
          }
          }
          }





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53360091%2fsymfony-eventsubscribe-on-entity%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            Doctrine has it's own events handler/subscriber system. However, with the class SymfonyComponentEventDispatcherEventSubscriberInterface; that you are implementing, that is from the Symfony event system.



            <?php
            use DoctrineORMEvents;
            use DoctrineCommonEventSubscriber; // **the Doctrine Event subscriber interface**
            use DoctrineCommonPersistenceEventLifecycleEventArgs;

            class MyEventSubscriber implements EventSubscriber
            {
            public function getSubscribedEvents()
            {
            return array(
            Events::postUpdate,
            );
            }

            public function postUpdate(LifecycleEventArgs $args)
            {
            $entity = $args->getObject();
            $entityManager = $args->getObjectManager();

            // perhaps you only want to act on some "Product" entity
            if ($entity instanceof Product) {
            // do something with the Product
            }
            }
            }





            share|improve this answer

























              up vote
              1
              down vote



              accepted










              Doctrine has it's own events handler/subscriber system. However, with the class SymfonyComponentEventDispatcherEventSubscriberInterface; that you are implementing, that is from the Symfony event system.



              <?php
              use DoctrineORMEvents;
              use DoctrineCommonEventSubscriber; // **the Doctrine Event subscriber interface**
              use DoctrineCommonPersistenceEventLifecycleEventArgs;

              class MyEventSubscriber implements EventSubscriber
              {
              public function getSubscribedEvents()
              {
              return array(
              Events::postUpdate,
              );
              }

              public function postUpdate(LifecycleEventArgs $args)
              {
              $entity = $args->getObject();
              $entityManager = $args->getObjectManager();

              // perhaps you only want to act on some "Product" entity
              if ($entity instanceof Product) {
              // do something with the Product
              }
              }
              }





              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                Doctrine has it's own events handler/subscriber system. However, with the class SymfonyComponentEventDispatcherEventSubscriberInterface; that you are implementing, that is from the Symfony event system.



                <?php
                use DoctrineORMEvents;
                use DoctrineCommonEventSubscriber; // **the Doctrine Event subscriber interface**
                use DoctrineCommonPersistenceEventLifecycleEventArgs;

                class MyEventSubscriber implements EventSubscriber
                {
                public function getSubscribedEvents()
                {
                return array(
                Events::postUpdate,
                );
                }

                public function postUpdate(LifecycleEventArgs $args)
                {
                $entity = $args->getObject();
                $entityManager = $args->getObjectManager();

                // perhaps you only want to act on some "Product" entity
                if ($entity instanceof Product) {
                // do something with the Product
                }
                }
                }





                share|improve this answer












                Doctrine has it's own events handler/subscriber system. However, with the class SymfonyComponentEventDispatcherEventSubscriberInterface; that you are implementing, that is from the Symfony event system.



                <?php
                use DoctrineORMEvents;
                use DoctrineCommonEventSubscriber; // **the Doctrine Event subscriber interface**
                use DoctrineCommonPersistenceEventLifecycleEventArgs;

                class MyEventSubscriber implements EventSubscriber
                {
                public function getSubscribedEvents()
                {
                return array(
                Events::postUpdate,
                );
                }

                public function postUpdate(LifecycleEventArgs $args)
                {
                $entity = $args->getObject();
                $entityManager = $args->getObjectManager();

                // perhaps you only want to act on some "Product" entity
                if ($entity instanceof Product) {
                // do something with the Product
                }
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 18 at 11:20









                Alister Bulman

                25.1k55599




                25.1k55599






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53360091%2fsymfony-eventsubscribe-on-entity%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Paul Cézanne

                    UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

                    Angular material date-picker (MatDatepicker) auto completes the date on focus out