Get the configured transport from mailer service

Is there a better way to get the transport from mailer service than this?

//the container function is marked as @internal
$mailer = \Pimcore::getContainer()->get(‘mailer’);

$transport = $mailer->getTransport();

Considering I can’t use dependency injection on the class I am doing it.

Why, exactly, can’t you use dependency injection?

I think because the code is something like this:

$this->thirdPartyLibrary->doMagic(MyClass::class);

Then inside this third party library my class is instantiated by using the new keyword and a method in the interface I implemented is called.

Why not then create an Event in your class and add an event listener which sends a mail? Then you get dependency injection for the listener.

1 Like

Nice idea but this third party library expects a configured Swift_Transport to be returned from the interface method that I am implementing.

I see. That’s tough. The hard part there is that the third party library creates a new instance of the class passed to it. I mean, that’s counter-intuitive.

Yeah, I don’t think there’s a better way than that, I’m afraid. You’ll have to rely on the container.

That’s unfortunate, but hey, do you have an example of how to setup the event listener with dependency injection?
Might be useful in the future.

Well, an event listener is a service as any other. So, you would do this in the services.yml:

name.of.your.event.listener:
    class: \Path\To\Your\Event\Listener
    arguments:
        - '@some_service_which_needs_to_be_injected
    tags:
        - { name: kernel.event_listener, event: some.event.you.need.to.listen.to, method: yourListenerMethod }

And in the \Path\To\Your\Event\Listener class, do this:

<?php

namespace \Path\To\Your\Event;

use \Path\To\SomeServiceWhichNeedsToBeInjected;
use Pimcore\Event\Model\ElementEventInterface;

class Listener
{
    /** @var SomeServiceWhichNeedsToBeInjected */
    private $someServiceWhichNeedsToBeInjected;

    public function __construct(
        SomeServiceWhichNeedsToBeInjected $someServiceWhichNeedsToBeInjected
    ) {
        $this->someServiceWhichNeedsToBeInjected = someServiceWhichNeedsToBeInjected;
    }

    public function yourListenerMethod (ElementEventInterface $event)
    {
        // assuming you're listening to some sort of Pimcore event
        if ($event instance of DataObjectEvent) {
            $this->someServiceWhichNeedsToBeInjected->someServiceMethod($parameters);
        }
    }
}

Hope this helps.

Thank you very much!