Skip to content

Commit 525eea1

Browse files
authored
Update multiple services example
This PR propose to replace SwiftMailer with the Mailer component and to add the Logger service for a better understanding how to inject multiple services
1 parent f64cd98 commit 525eea1

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

service_container.rst

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -295,34 +295,46 @@ made. To do that, you create a new class::
295295
namespace App\Updates;
296296

297297
use App\Service\MessageGenerator;
298+
use Psr\Log\LoggerInterface;
299+
use Symfony\Component\Mailer\MailerInterface;
300+
use Symfony\Component\Mime\Email;
298301

299302
class SiteUpdateManager
300303
{
301304
private $messageGenerator;
302305
private $mailer;
306+
private $logger;
303307

304-
public function __construct(MessageGenerator $messageGenerator, \Swift_Mailer $mailer)
308+
public function __construct(MessageGenerator $messageGenerator, MailerInterface $mailer, LoggerInterface $logger)
305309
{
306310
$this->messageGenerator = $messageGenerator;
307311
$this->mailer = $mailer;
312+
$this-logger = $logger;
308313
}
309314

310-
public function notifyOfSiteUpdate()
315+
public function notifyOfSiteUpdate(): bool
311316
{
312317
$happyMessage = $this->messageGenerator->getHappyMessage();
313318

314-
$message = (new \Swift_Message('Site update just happened!'))
315-
->setFrom('admin@example.com')
316-
->setTo('manager@example.com')
317-
->addPart(
318-
'Someone just updated the site. We told them: '.$happyMessage
319-
);
319+
try {
320+
$email = (new Email())
321+
->from('admin@example.com')
322+
->to('manager@example.com')
323+
->subject('Site update just happened!')
324+
->text('Someone just updated the site. We told them: '.$happyMessage);
320325

321-
return $this->mailer->send($message) > 0;
326+
$this->mailer->send($email);
327+
328+
return true;
329+
} catch (\Exception $exception) {
330+
$this->logger->error($exception->getMessage());
331+
332+
return false;
333+
}
322334
}
323335
}
324336

325-
This needs the ``MessageGenerator`` *and* the ``Swift_Mailer`` service. That's no
337+
This needs the ``MessageGenerator`` *and* both ``Mailer`` and ``Logger`` services. That's no
326338
problem! In fact, this new service is ready to be used. In a controller, for example,
327339
you can type-hint the new ``SiteUpdateManager`` class and use it::
328340

0 commit comments

Comments
 (0)