Search code examples
symfonyevent-listenerswiftmailer

Symfony 3.4 - how would one pass Swiftmailer into an event listener?


I'm building an e-commerce app using Stripe. I currently have several event listeners that talk to Stripe via its API when certain things happen (e.g. a Customer, Product, or SKU getting created or updated). Because these API calls can produce several Exceptions, I'd like to have the app email me in certain cases.

So, how would I configure my services.yml to pass Swiftmailer to my listeners? My current setup (single example, but they all more or less look like this):

AppBundle\EventListener\UserHandler:
        arguments:
            $stripeKey: "%secret_stripe_key%"
            $session: "@session"
            $logger: "@monolog.logger"
        tags:
            - { name: doctrine.event_listener, event: prePersist }
            - { name: doctrine.event_listener, event: preUpdate }

Is the resource tag simply "@swiftmailer"? And what namespace(s) should I be using in my listeners?


Solution

  • As suggested above, I would use autowiring. This will prevent you from having to add code to your services.yml and is the way to go as of Symfony 3.3.

    In your constructor of UserHandler:

    __construct(Swift_Mailer $mailer, SessionInterface $session, LoggerInterface $logger) {
      $this->mailer = $mailer;
      $this->logger = $logger;
      $this->session = $session;
    }
    

    So in your functions you can now call $this->mailer which will be autowired because of the typehinting in the constructor. Same goes for Session & Logger. To find out which service you're looking for you can execute the following: bin/console debug:autowiring

    Make sure you include the classes above in the use-statements