Search code examples
phpzend-frameworkzend-framework2

Setting up default transport method in Zend Framework 2.4 for Zend\Mail\Message


We are currently rewriting part of our project to use SMTP when sending out E-Mails via our Zend Framework 2.4-Application.

We have about 25 seperate cases, where we use Zend\Mail\Transport\Sendmail to send E-Mails, however they do not use SMTP. I started to rewrite

$transport = new Sendmail();
$transport->send($message);

to

$transport = new SmtpTransport();
$options   = new SmtpOptions(array(
          'name' => $this->_config['smtp']['name'],
          'host' => $this->_config['smtp']['host'],
));
$transport->setOptions($options);
$transport->send($message);

This works, but I don't feel like rewriting every single instance of that, so I googled a bit and found this on the Zend Framework Website (for ZF1.X)

$tr = new Zend_Mail_Transport_Smtp('mail.example.com');
Zend_Mail::setDefaultTransport($tr);

However, this is no longer possible in Zend Framework 2.4 as the setDefaultTransport method is gone.

I searched around for a bit on how to recreate this in 2.4, but I did not find a solution.

Any help is greatly appreciated.


Solution

  • This is a perfect example of why we use dependency injection.

    https://framework.zend.com/manual/2.4/en/modules/zend.di.quick-start.html

    Take a look at the service manager too

    https://framework.zend.com/manual/2.1/en/modules/zend.service-manager.intro.html

    Define your service only once