Micha
Micha

Reputation: 43

creating a mailer service in symfony 2

I'm very new to Symfony and now I have a question about configuring and sending a mail. Actually I'm configuring and sending the mail in the controller, but for me it would be better to configure the mail not in the controller, but in an .ini-file or something else. Therefore I thought the right way would be to configure it as a service, because so I can configure the mail itself in a class and not in the code.

I created a class, that looks like that:

class PwMailer{
protected $mailer;

public function setMailer($mailer)
{
    $this->mailer = $mailer;
}

public function sendEmail($email, $password)
{
    $message = \Swift_Message::newInstance()
        ->setSubject('New Password')
        ->setFrom('[email protected]')
        ->setTo($email)
        ->setBody('Your new Password is '.$password)
    ;
    $this->mailer->send($message);
}

}

The values $email and $password should come from the controller. In my config-file app\config\config.yml I configured it:

services:
  pw_mailer:
    class:     Pso\LogBundle\PwMailer
    arguments: [sendmail] 

I call the service from controller

$mailer = new Mailer('pw_mailer');
$mailer->send();

Now I got the error "FatalErrorException: Error: Class '...Mailer' not found in '...controller'

My code is a Mix from http://symfony.com/doc/current/book/service_container.html and How can I send emails from a Symfony2 service class?

I would be glad about a hint, if a service container for configuring the mail in a class and not in the controller is the right way and where my mistake in thinking is. Until now I didn't unterstand how the configuration of a service container exactly works.

Greetings

Upvotes: 1

Views: 2091

Answers (1)

ReynierPM
ReynierPM

Reputation: 18690

Your service has an external dependency, notably the mailer service. You can either inject the service container itself, or inject the mailer service. If your service only requires the mailer service and nothing else, I would suggest injecting just the mailer service. Here is how you would configure the DIC to inject the mailer service using a setter:

services:
    pw_mailer:
        class:     Pso\LogBundle\PwMailer
        arguments: [mailer]

Upvotes: 0

Related Questions