Seems doctrine listener is not fired

Posted by Roel Veldhuizen on Stack Overflow See other posts from Stack Overflow or by Roel Veldhuizen
Published on 2013-10-11T12:14:02Z Indexed on 2013/10/18 9:55 UTC
Read the original article Hit count: 656

Filed under:
|

Got a service which should be executed the moment an object is persisted. Though, I think the code looks like it should work, it doesn't. I configured the service like the following yml.

services:    
    bla_orm.listener:
        class: Bla\OrmBundle\EventListener\UserManager
        arguments: [@security.encoder_factory] 
        tags:
            - { name: doctrine.event_listener, event: prePersist }

The class:

namespace Bla\OrmBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Bla\OrmBundle\Entity\User;

class UserManager {

        protected $encoderFactory;

        public function __construct(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface $encoderFactory) {
            $this->encoderFactory = $encoderFactory;
        }

        public function prePersist(LifecycleEventArgs $args) {
            $entity = $args->getEntity();

            if ($entity instanceof User) {

                $encoder = $this->encoderFactory ->getEncoder($entity);
                $entity->setSalt(rand(10000, 99999));
                $password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
                $entity->setPassword($password);
            }
        }

    }

Symfony version:

Symfony version 2.3.3 - app/dev/debug

Output of container:debug

[container] Public services
Service Id                                      Scope     Class Name
annotation_reader                               container Doctrine\Common\Annotations\FileCacheReader
assetic.asset_manager                           container Assetic\Factory\LazyAssetManager
assetic.controller                              prototype Symfony\Bundle\AsseticBundle\Controller\AsseticController
assetic.filter.cssrewrite                       container Assetic\Filter\CssRewriteFilter
assetic.filter_manager                          container Symfony\Bundle\AsseticBundle\FilterManager
assetic.request_listener                        container Symfony\Bundle\AsseticBundle\EventListener\RequestListener
cache_clearer                                   container Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer
cache_warmer                                    container Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate
data_collector.request                          container Symfony\Component\HttpKernel\DataCollector\RequestDataCollector
data_collector.router                           container Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector
database_connection                             n/a       alias for doctrine.dbal.default_connection
debug.controller_resolver                       container Symfony\Component\HttpKernel\Controller\TraceableControllerResolver
debug.deprecation_logger_listener               container Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener
debug.emergency_logger_listener                 container Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener
debug.event_dispatcher                          container Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher
debug.stopwatch                                 container Symfony\Component\Stopwatch\Stopwatch
debug.templating.engine.php                     container Symfony\Bundle\FrameworkBundle\Templating\TimedPhpEngine
debug.templating.engine.twig                    n/a       alias for templating
doctrine                                        container Doctrine\Bundle\DoctrineBundle\Registry
doctrine.dbal.connection_factory                container Doctrine\Bundle\DoctrineBundle\ConnectionFactory
doctrine.dbal.default_connection                container stdClass
doctrine.orm.default_entity_manager             container Doctrine\ORM\EntityManager
doctrine.orm.default_manager_configurator       container Doctrine\Bundle\DoctrineBundle\ManagerConfigurator
doctrine.orm.entity_manager                     n/a       alias for doctrine.orm.default_entity_manager
doctrine.orm.validator.unique                   container Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator
doctrine.orm.validator_initializer              container Symfony\Bridge\Doctrine\Validator\DoctrineInitializer
event_dispatcher                                container Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
file_locator                                    container Symfony\Component\HttpKernel\Config\FileLocator
filesystem                                      container Symfony\Component\Filesystem\Filesystem
form.csrf_provider                              container Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider
form.factory                                    container Symfony\Component\Form\FormFactory
form.registry                                   container Symfony\Component\Form\FormRegistry
form.resolved_type_factory                      container Symfony\Component\Form\ResolvedFormTypeFactory
form.type.birthday                              container Symfony\Component\Form\Extension\Core\Type\BirthdayType
form.type.button                                container Symfony\Component\Form\Extension\Core\Type\ButtonType
form.type.checkbox                              container Symfony\Component\Form\Extension\Core\Type\CheckboxType
form.type.choice                                container Symfony\Component\Form\Extension\Core\Type\ChoiceType
form.type.collection                            container Symfony\Component\Form\Extension\Core\Type\CollectionType
form.type.country                               container Symfony\Component\Form\Extension\Core\Type\CountryType
form.type.currency                              container Symfony\Component\Form\Extension\Core\Type\CurrencyType
form.type.date                                  container Symfony\Component\Form\Extension\Core\Type\DateType
form.type.datetime                              container Symfony\Component\Form\Extension\Core\Type\DateTimeType
form.type.email                                 container Symfony\Component\Form\Extension\Core\Type\EmailType
form.type.entity                                container Symfony\Bridge\Doctrine\Form\Type\EntityType
form.type.file                                  container Symfony\Component\Form\Extension\Core\Type\FileType
form.type.form                                  container Symfony\Component\Form\Extension\Core\Type\FormType
form.type.hidden                                container Symfony\Component\Form\Extension\Core\Type\HiddenType
form.type.integer                               container Symfony\Component\Form\Extension\Core\Type\IntegerType
form.type.language                              container Symfony\Component\Form\Extension\Core\Type\LanguageType
form.type.locale                                container Symfony\Component\Form\Extension\Core\Type\LocaleType
form.type.money                                 container Symfony\Component\Form\Extension\Core\Type\MoneyType
form.type.number                                container Symfony\Component\Form\Extension\Core\Type\NumberType
form.type.password                              container Symfony\Component\Form\Extension\Core\Type\PasswordType
form.type.percent                               container Symfony\Component\Form\Extension\Core\Type\PercentType
form.type.radio                                 container Symfony\Component\Form\Extension\Core\Type\RadioType
form.type.repeated                              container Symfony\Component\Form\Extension\Core\Type\RepeatedType
form.type.reset                                 container Symfony\Component\Form\Extension\Core\Type\ResetType
form.type.search                                container Symfony\Component\Form\Extension\Core\Type\SearchType
form.type.submit                                container Symfony\Component\Form\Extension\Core\Type\SubmitType
form.type.text                                  container Symfony\Component\Form\Extension\Core\Type\TextType
form.type.textarea                              container Symfony\Component\Form\Extension\Core\Type\TextareaType
form.type.time                                  container Symfony\Component\Form\Extension\Core\Type\TimeType
form.type.timezone                              container Symfony\Component\Form\Extension\Core\Type\TimezoneType
form.type.url                                   container Symfony\Component\Form\Extension\Core\Type\UrlType
form.type_extension.csrf                        container Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension
form.type_extension.form.http_foundation        container Symfony\Component\Form\Extension\HttpFoundation\Type\FormTypeHttpFoundationExtension
form.type_extension.form.validator              container Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension
form.type_extension.repeated.validator          container Symfony\Component\Form\Extension\Validator\Type\RepeatedTypeValidatorExtension
form.type_extension.submit.validator            container Symfony\Component\Form\Extension\Validator\Type\SubmitTypeValidatorExtension
form.type_guesser.doctrine                      container Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser
form.type_guesser.validator                     container Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser
fragment.handler                                container Symfony\Component\HttpKernel\Fragment\FragmentHandler
fragment.listener                               container Symfony\Component\HttpKernel\EventListener\FragmentListener
fragment.renderer.hinclude                      container Symfony\Bundle\FrameworkBundle\Fragment\ContainerAwareHIncludeFragmentRenderer
fragment.renderer.inline                        container Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer
http_kernel                                     container Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel
kernel                                          container 
locale_listener                                 container Symfony\Component\HttpKernel\EventListener\LocaleListener
logger                                          container Symfony\Bridge\Monolog\Logger
mailer                                          n/a       alias for swiftmailer.mailer.default
monolog.handler.chromephp                       container Symfony\Bridge\Monolog\Handler\ChromePhpHandler
monolog.handler.debug                           container Symfony\Bridge\Monolog\Handler\DebugHandler
monolog.handler.firephp                         container Symfony\Bridge\Monolog\Handler\FirePHPHandler
monolog.handler.main                            container Monolog\Handler\StreamHandler
monolog.logger.deprecation                      container Symfony\Bridge\Monolog\Logger
monolog.logger.doctrine                         container Symfony\Bridge\Monolog\Logger
monolog.logger.emergency                        container Symfony\Bridge\Monolog\Logger
monolog.logger.event                            container Symfony\Bridge\Monolog\Logger
monolog.logger.profiler                         container Symfony\Bridge\Monolog\Logger
monolog.logger.request                          container Symfony\Bridge\Monolog\Logger
monolog.logger.router                           container Symfony\Bridge\Monolog\Logger
monolog.logger.security                         container Symfony\Bridge\Monolog\Logger
monolog.logger.templating                       container Symfony\Bridge\Monolog\Logger
profiler                                        container Symfony\Component\HttpKernel\Profiler\Profiler
profiler_listener                               container Symfony\Component\HttpKernel\EventListener\ProfilerListener
property_accessor                               container Symfony\Component\PropertyAccess\PropertyAccessor
request                                         request   
response_listener                               container Symfony\Component\HttpKernel\EventListener\ResponseListener
router                                          container Symfony\Bundle\FrameworkBundle\Routing\Router
router_listener                                 container Symfony\Component\HttpKernel\EventListener\RouterListener
routing.loader                                  container Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader
security.context                                container Symfony\Component\Security\Core\SecurityContext
security.encoder_factory                        container Symfony\Component\Security\Core\Encoder\EncoderFactory
security.firewall                               container Symfony\Component\Security\Http\Firewall
security.firewall.map.context.dev               container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.firewall.map.context.login             container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.firewall.map.context.rest              container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.firewall.map.context.secured_area      container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.rememberme.response_listener           container Symfony\Component\Security\Http\RememberMe\ResponseListener
security.secure_random                          container Symfony\Component\Security\Core\Util\SecureRandom
security.validator.user_password                container Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator
sensio.distribution.webconfigurator             n/a       alias for sensio_distribution.webconfigurator
sensio_distribution.webconfigurator             container Sensio\Bundle\DistributionBundle\Configurator\Configurator
sensio_framework_extra.cache.listener           container Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener
sensio_framework_extra.controller.listener      container Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener
sensio_framework_extra.converter.datetime       container Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DateTimeParamConverter
sensio_framework_extra.converter.doctrine.orm   container Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter
sensio_framework_extra.converter.listener       container Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener
sensio_framework_extra.converter.manager        container Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterManager
sensio_framework_extra.view.guesser             container Sensio\Bundle\FrameworkExtraBundle\Templating\TemplateGuesser
sensio_framework_extra.view.listener            container Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener
service_container                               container 
session                                         container Symfony\Component\HttpFoundation\Session\Session
session.handler                                 container Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler
session.storage                                 n/a       alias for session.storage.native
session.storage.filesystem                      container Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage
session.storage.native                          container Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage
session.storage.php_bridge                      container Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage
session_listener                                container Symfony\Bundle\FrameworkBundle\EventListener\SessionListener
streamed_response_listener                      container Symfony\Component\HttpKernel\EventListener\StreamedResponseListener
swiftmailer.email_sender.listener               container Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener
swiftmailer.mailer                              n/a       alias for swiftmailer.mailer.default
swiftmailer.mailer.default                      container Swift_Mailer
swiftmailer.mailer.default.plugin.messagelogger container Swift_Plugins_MessageLogger
swiftmailer.mailer.default.spool                container Swift_FileSpool
swiftmailer.mailer.default.transport            container Swift_Transport_SpoolTransport
swiftmailer.mailer.default.transport.real       container Swift_Transport_EsmtpTransport
swiftmailer.plugin.messagelogger                n/a       alias for swiftmailer.mailer.default.plugin.messagelogger
swiftmailer.spool                               n/a       alias for swiftmailer.mailer.default.spool
swiftmailer.transport                           n/a       alias for swiftmailer.mailer.default.transport
swiftmailer.transport.real                      n/a       alias for swiftmailer.mailer.default.transport.real
templating                                      container Symfony\Bundle\TwigBundle\Debug\TimedTwigEngine
templating.asset.package_factory                container Symfony\Bundle\FrameworkBundle\Templating\Asset\PackageFactory
templating.filename_parser                      container Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser
templating.globals                              container Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables
templating.helper.actions                       container Symfony\Bundle\FrameworkBundle\Templating\Helper\ActionsHelper
templating.helper.assets                        request   Symfony\Component\Templating\Helper\CoreAssetsHelper
templating.helper.code                          container Symfony\Bundle\FrameworkBundle\Templating\Helper\CodeHelper
templating.helper.form                          container Symfony\Bundle\FrameworkBundle\Templating\Helper\FormHelper
templating.helper.logout_url                    container Symfony\Bundle\SecurityBundle\Templating\Helper\LogoutUrlHelper
templating.helper.request                       container Symfony\Bundle\FrameworkBundle\Templating\Helper\RequestHelper
templating.helper.router                        container Symfony\Bundle\FrameworkBundle\Templating\Helper\RouterHelper
templating.helper.security                      container Symfony\Bundle\SecurityBundle\Templating\Helper\SecurityHelper
templating.helper.session                       container Symfony\Bundle\FrameworkBundle\Templating\Helper\SessionHelper
templating.helper.slots                         container Symfony\Component\Templating\Helper\SlotsHelper
templating.helper.translator                    container Symfony\Bundle\FrameworkBundle\Templating\Helper\TranslatorHelper
templating.loader                               container Symfony\Bundle\FrameworkBundle\Templating\Loader\FilesystemLoader
templating.name_parser                          container Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser
translation.dumper.csv                          container Symfony\Component\Translation\Dumper\CsvFileDumper
translation.dumper.ini                          container Symfony\Component\Translation\Dumper\IniFileDumper
translation.dumper.mo                           container Symfony\Component\Translation\Dumper\MoFileDumper
translation.dumper.php                          container Symfony\Component\Translation\Dumper\PhpFileDumper
translation.dumper.po                           container Symfony\Component\Translation\Dumper\PoFileDumper
translation.dumper.qt                           container Symfony\Component\Translation\Dumper\QtFileDumper
translation.dumper.res                          container Symfony\Component\Translation\Dumper\IcuResFileDumper
translation.dumper.xliff                        container Symfony\Component\Translation\Dumper\XliffFileDumper
translation.dumper.yml                          container Symfony\Component\Translation\Dumper\YamlFileDumper
translation.extractor                           container Symfony\Component\Translation\Extractor\ChainExtractor
translation.extractor.php                       container Symfony\Bundle\FrameworkBundle\Translation\PhpExtractor
translation.loader                              container Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader
translation.loader.csv                          container Symfony\Component\Translation\Loader\CsvFileLoader
translation.loader.dat                          container Symfony\Component\Translation\Loader\IcuResFileLoader
translation.loader.ini                          container Symfony\Component\Translation\Loader\IniFileLoader
translation.loader.mo                           container Symfony\Component\Translation\Loader\MoFileLoader
translation.loader.php                          container Symfony\Component\Translation\Loader\PhpFileLoader
translation.loader.po                           container Symfony\Component\Translation\Loader\PoFileLoader
translation.loader.qt                           container Symfony\Component\Translation\Loader\QtFileLoader
translation.loader.res                          container Symfony\Component\Translation\Loader\IcuResFileLoader
translation.loader.xliff                        container Symfony\Component\Translation\Loader\XliffFileLoader
translation.loader.yml                          container Symfony\Component\Translation\Loader\YamlFileLoader
translation.writer                              container Symfony\Component\Translation\Writer\TranslationWriter
translator                                      n/a       alias for translator.default
translator.default                              container Symfony\Bundle\FrameworkBundle\Translation\Translator
twig                                            container Twig_Environment
twig.controller.exception                       container Symfony\Bundle\TwigBundle\Controller\ExceptionController
twig.exception_listener                         container Symfony\Component\HttpKernel\EventListener\ExceptionListener
twig.loader                                     container Symfony\Bundle\TwigBundle\Loader\FilesystemLoader
twig.translation.extractor                      container Symfony\Bridge\Twig\Translation\TwigExtractor
uri_signer                                      container Symfony\Component\HttpKernel\UriSigner
bla_orm.listener                                container Bla\OrmBundle\EventListener\UserManager
validator                                       container Symfony\Component\Validator\Validator
web_profiler.controller.exception               container Symfony\Bundle\WebProfilerBundle\Controller\ExceptionController
web_profiler.controller.profiler                container Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController
web_profiler.controller.router                  container Symfony\Bundle\WebProfilerBundle\Controller\RouterController
web_profiler.debug_toolbar                      container Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener

Update

It seems that the listener is not invoked when an updateAction, generated by generate:doctrine:crud has taken place though. At another part of the code the lister seems to be invoked. Though, there are both Controller types and both us $em->persist($something); $em->flush(); to save the changes. I would expect that in both cases the listener is invoked.

© Stack Overflow or respective owner

Related posts about symfony2

Related posts about doctrine2