Symfony 4 Accessing Swift_Mailer in Service












0














I have been looking at the Symfony 4.1 documentation on using the Swift_mailer. However, it appears the documentation is only assumed it being used in the Controller classes. I'm trying to create a Service with some reusable functions that send email.



I created a EmailService.php file in my service directory. When creating a new instance of this service, it quickly throws and error:




"Too few arguments to function
AppServiceEmailService::__construct(), 0 passed in
*MyAppsrcControllerTestController.php on line 33
and exactly 1 expected"




I'm not sure how to pass Swift_Mailer $mailer into the __construct correctly? I have auto wiring enabled in the services.yaml, so i'm not sure what I need to do differently?



class EmailService
{
private $from = 'support@******.com';
private $mailer;

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


How do I pass the Swift_Mailer into this EmailService construct?



I tried adding this to my configservices.yaml with no success:



AppServiceEmailService:
arguments: ['@mailer']









share|improve this question


















  • 4




    And how are you trying to access your EmailService? I suspect you are trying to new it.
    – Cerad
    Nov 13 '18 at 3:27










  • Correct, "new EmailService()"
    – Speedy059
    Nov 13 '18 at 3:38






  • 1




    Please use either Constructor injection or inject the service into your action by just adding it as argument to the method e.g. public function index(Request $request, EmailService $emailService) {...}.
    – dbrumann
    Nov 13 '18 at 8:06


















0














I have been looking at the Symfony 4.1 documentation on using the Swift_mailer. However, it appears the documentation is only assumed it being used in the Controller classes. I'm trying to create a Service with some reusable functions that send email.



I created a EmailService.php file in my service directory. When creating a new instance of this service, it quickly throws and error:




"Too few arguments to function
AppServiceEmailService::__construct(), 0 passed in
*MyAppsrcControllerTestController.php on line 33
and exactly 1 expected"




I'm not sure how to pass Swift_Mailer $mailer into the __construct correctly? I have auto wiring enabled in the services.yaml, so i'm not sure what I need to do differently?



class EmailService
{
private $from = 'support@******.com';
private $mailer;

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


How do I pass the Swift_Mailer into this EmailService construct?



I tried adding this to my configservices.yaml with no success:



AppServiceEmailService:
arguments: ['@mailer']









share|improve this question


















  • 4




    And how are you trying to access your EmailService? I suspect you are trying to new it.
    – Cerad
    Nov 13 '18 at 3:27










  • Correct, "new EmailService()"
    – Speedy059
    Nov 13 '18 at 3:38






  • 1




    Please use either Constructor injection or inject the service into your action by just adding it as argument to the method e.g. public function index(Request $request, EmailService $emailService) {...}.
    – dbrumann
    Nov 13 '18 at 8:06
















0












0








0







I have been looking at the Symfony 4.1 documentation on using the Swift_mailer. However, it appears the documentation is only assumed it being used in the Controller classes. I'm trying to create a Service with some reusable functions that send email.



I created a EmailService.php file in my service directory. When creating a new instance of this service, it quickly throws and error:




"Too few arguments to function
AppServiceEmailService::__construct(), 0 passed in
*MyAppsrcControllerTestController.php on line 33
and exactly 1 expected"




I'm not sure how to pass Swift_Mailer $mailer into the __construct correctly? I have auto wiring enabled in the services.yaml, so i'm not sure what I need to do differently?



class EmailService
{
private $from = 'support@******.com';
private $mailer;

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


How do I pass the Swift_Mailer into this EmailService construct?



I tried adding this to my configservices.yaml with no success:



AppServiceEmailService:
arguments: ['@mailer']









share|improve this question













I have been looking at the Symfony 4.1 documentation on using the Swift_mailer. However, it appears the documentation is only assumed it being used in the Controller classes. I'm trying to create a Service with some reusable functions that send email.



I created a EmailService.php file in my service directory. When creating a new instance of this service, it quickly throws and error:




"Too few arguments to function
AppServiceEmailService::__construct(), 0 passed in
*MyAppsrcControllerTestController.php on line 33
and exactly 1 expected"




I'm not sure how to pass Swift_Mailer $mailer into the __construct correctly? I have auto wiring enabled in the services.yaml, so i'm not sure what I need to do differently?



class EmailService
{
private $from = 'support@******.com';
private $mailer;

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


How do I pass the Swift_Mailer into this EmailService construct?



I tried adding this to my configservices.yaml with no success:



AppServiceEmailService:
arguments: ['@mailer']






symfony swiftmailer symfony4






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 1:05









Speedy059Speedy059

1079




1079








  • 4




    And how are you trying to access your EmailService? I suspect you are trying to new it.
    – Cerad
    Nov 13 '18 at 3:27










  • Correct, "new EmailService()"
    – Speedy059
    Nov 13 '18 at 3:38






  • 1




    Please use either Constructor injection or inject the service into your action by just adding it as argument to the method e.g. public function index(Request $request, EmailService $emailService) {...}.
    – dbrumann
    Nov 13 '18 at 8:06
















  • 4




    And how are you trying to access your EmailService? I suspect you are trying to new it.
    – Cerad
    Nov 13 '18 at 3:27










  • Correct, "new EmailService()"
    – Speedy059
    Nov 13 '18 at 3:38






  • 1




    Please use either Constructor injection or inject the service into your action by just adding it as argument to the method e.g. public function index(Request $request, EmailService $emailService) {...}.
    – dbrumann
    Nov 13 '18 at 8:06










4




4




And how are you trying to access your EmailService? I suspect you are trying to new it.
– Cerad
Nov 13 '18 at 3:27




And how are you trying to access your EmailService? I suspect you are trying to new it.
– Cerad
Nov 13 '18 at 3:27












Correct, "new EmailService()"
– Speedy059
Nov 13 '18 at 3:38




Correct, "new EmailService()"
– Speedy059
Nov 13 '18 at 3:38




1




1




Please use either Constructor injection or inject the service into your action by just adding it as argument to the method e.g. public function index(Request $request, EmailService $emailService) {...}.
– dbrumann
Nov 13 '18 at 8:06






Please use either Constructor injection or inject the service into your action by just adding it as argument to the method e.g. public function index(Request $request, EmailService $emailService) {...}.
– dbrumann
Nov 13 '18 at 8:06














2 Answers
2






active

oldest

votes


















0














As mentioned by dbrumann in a comment, I needed to follow the proper way of injecting services.



First, I needed to add the services to config/services.yaml



#config/services.yaml
emailservice:
class: AppServiceEmailService
arguments: ['@swiftmailer.mailer.default', '@twig']
public: true


Second, I need to setup the service to accept both the mailer, and twig for rendering the template.



#App/Service/EmailService.php
<?php
namespace AppService;

class EmailService
{
private $from = 'support@*****.com';
private $mailer;
private $templating;

public function __construct(Swift_Mailer $mailer, TwigEnvironment $templating)
{
$this->mailer = $mailer;
$this->templating = $templating;
}
public function userConfirmation(string $recipient, string $confCode) : bool
{

$message = (new Swift_Message())
->setSubject('Some sort of string')
->setFrom($this->from)
->setTo($recipient)
->setBody(
$this->templating->render(
'email/UserConfirmation.html.twig',
array('confCode' => $confCode)
),
'text/html'
)
/*
* If you also want to include a plaintext version of the message
->addPart(
$this->renderView(
'emails/UserConfirmation.txt.twig',
array('confCode' => $confCode)
),
'text/plain'
)
*/
;
return $this->mailer->send($message);
}
}


Third, to call it from the controller, make sure your controller is extending Controller and not the AbstractController! Crucial step!! Here is an example based on the parameters I require in my service:



public function userConfirmation()
{
$emailService = $this->get('emailservice');
$sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
return new Response('Success') //Or whatever you want to return
}


I hope this helps people. AbstractController does not give you the proper access to the service containers.






share|improve this answer





























    0














    Try :



    #config/services.yaml

    AppServiceEmailService
    arguments: ['@swiftmailer.mailer.default', '@twig']
    public: true


    And in your controller :



    public function userConfirmation(EmailService $emailService)
    {
    $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
    return new Response('Success') //Or whatever you want to return
    }


    You work with symfony 4.1 so you don't call service container in controller anymore ...
    https://symfony.com/doc/current/service_container/3.3-di-changes.html



    Also you can use FQCN "AppServiceMyService" to declare services in services.yaml and a proper legacy_aliases.yaml file to declare legacy aliases like "app.service.my.service" it helps keep your services.yaml clean in my opinion ...






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53272302%2fsymfony-4-accessing-swift-mailer-in-service%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      As mentioned by dbrumann in a comment, I needed to follow the proper way of injecting services.



      First, I needed to add the services to config/services.yaml



      #config/services.yaml
      emailservice:
      class: AppServiceEmailService
      arguments: ['@swiftmailer.mailer.default', '@twig']
      public: true


      Second, I need to setup the service to accept both the mailer, and twig for rendering the template.



      #App/Service/EmailService.php
      <?php
      namespace AppService;

      class EmailService
      {
      private $from = 'support@*****.com';
      private $mailer;
      private $templating;

      public function __construct(Swift_Mailer $mailer, TwigEnvironment $templating)
      {
      $this->mailer = $mailer;
      $this->templating = $templating;
      }
      public function userConfirmation(string $recipient, string $confCode) : bool
      {

      $message = (new Swift_Message())
      ->setSubject('Some sort of string')
      ->setFrom($this->from)
      ->setTo($recipient)
      ->setBody(
      $this->templating->render(
      'email/UserConfirmation.html.twig',
      array('confCode' => $confCode)
      ),
      'text/html'
      )
      /*
      * If you also want to include a plaintext version of the message
      ->addPart(
      $this->renderView(
      'emails/UserConfirmation.txt.twig',
      array('confCode' => $confCode)
      ),
      'text/plain'
      )
      */
      ;
      return $this->mailer->send($message);
      }
      }


      Third, to call it from the controller, make sure your controller is extending Controller and not the AbstractController! Crucial step!! Here is an example based on the parameters I require in my service:



      public function userConfirmation()
      {
      $emailService = $this->get('emailservice');
      $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
      return new Response('Success') //Or whatever you want to return
      }


      I hope this helps people. AbstractController does not give you the proper access to the service containers.






      share|improve this answer


























        0














        As mentioned by dbrumann in a comment, I needed to follow the proper way of injecting services.



        First, I needed to add the services to config/services.yaml



        #config/services.yaml
        emailservice:
        class: AppServiceEmailService
        arguments: ['@swiftmailer.mailer.default', '@twig']
        public: true


        Second, I need to setup the service to accept both the mailer, and twig for rendering the template.



        #App/Service/EmailService.php
        <?php
        namespace AppService;

        class EmailService
        {
        private $from = 'support@*****.com';
        private $mailer;
        private $templating;

        public function __construct(Swift_Mailer $mailer, TwigEnvironment $templating)
        {
        $this->mailer = $mailer;
        $this->templating = $templating;
        }
        public function userConfirmation(string $recipient, string $confCode) : bool
        {

        $message = (new Swift_Message())
        ->setSubject('Some sort of string')
        ->setFrom($this->from)
        ->setTo($recipient)
        ->setBody(
        $this->templating->render(
        'email/UserConfirmation.html.twig',
        array('confCode' => $confCode)
        ),
        'text/html'
        )
        /*
        * If you also want to include a plaintext version of the message
        ->addPart(
        $this->renderView(
        'emails/UserConfirmation.txt.twig',
        array('confCode' => $confCode)
        ),
        'text/plain'
        )
        */
        ;
        return $this->mailer->send($message);
        }
        }


        Third, to call it from the controller, make sure your controller is extending Controller and not the AbstractController! Crucial step!! Here is an example based on the parameters I require in my service:



        public function userConfirmation()
        {
        $emailService = $this->get('emailservice');
        $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
        return new Response('Success') //Or whatever you want to return
        }


        I hope this helps people. AbstractController does not give you the proper access to the service containers.






        share|improve this answer
























          0












          0








          0






          As mentioned by dbrumann in a comment, I needed to follow the proper way of injecting services.



          First, I needed to add the services to config/services.yaml



          #config/services.yaml
          emailservice:
          class: AppServiceEmailService
          arguments: ['@swiftmailer.mailer.default', '@twig']
          public: true


          Second, I need to setup the service to accept both the mailer, and twig for rendering the template.



          #App/Service/EmailService.php
          <?php
          namespace AppService;

          class EmailService
          {
          private $from = 'support@*****.com';
          private $mailer;
          private $templating;

          public function __construct(Swift_Mailer $mailer, TwigEnvironment $templating)
          {
          $this->mailer = $mailer;
          $this->templating = $templating;
          }
          public function userConfirmation(string $recipient, string $confCode) : bool
          {

          $message = (new Swift_Message())
          ->setSubject('Some sort of string')
          ->setFrom($this->from)
          ->setTo($recipient)
          ->setBody(
          $this->templating->render(
          'email/UserConfirmation.html.twig',
          array('confCode' => $confCode)
          ),
          'text/html'
          )
          /*
          * If you also want to include a plaintext version of the message
          ->addPart(
          $this->renderView(
          'emails/UserConfirmation.txt.twig',
          array('confCode' => $confCode)
          ),
          'text/plain'
          )
          */
          ;
          return $this->mailer->send($message);
          }
          }


          Third, to call it from the controller, make sure your controller is extending Controller and not the AbstractController! Crucial step!! Here is an example based on the parameters I require in my service:



          public function userConfirmation()
          {
          $emailService = $this->get('emailservice');
          $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
          return new Response('Success') //Or whatever you want to return
          }


          I hope this helps people. AbstractController does not give you the proper access to the service containers.






          share|improve this answer












          As mentioned by dbrumann in a comment, I needed to follow the proper way of injecting services.



          First, I needed to add the services to config/services.yaml



          #config/services.yaml
          emailservice:
          class: AppServiceEmailService
          arguments: ['@swiftmailer.mailer.default', '@twig']
          public: true


          Second, I need to setup the service to accept both the mailer, and twig for rendering the template.



          #App/Service/EmailService.php
          <?php
          namespace AppService;

          class EmailService
          {
          private $from = 'support@*****.com';
          private $mailer;
          private $templating;

          public function __construct(Swift_Mailer $mailer, TwigEnvironment $templating)
          {
          $this->mailer = $mailer;
          $this->templating = $templating;
          }
          public function userConfirmation(string $recipient, string $confCode) : bool
          {

          $message = (new Swift_Message())
          ->setSubject('Some sort of string')
          ->setFrom($this->from)
          ->setTo($recipient)
          ->setBody(
          $this->templating->render(
          'email/UserConfirmation.html.twig',
          array('confCode' => $confCode)
          ),
          'text/html'
          )
          /*
          * If you also want to include a plaintext version of the message
          ->addPart(
          $this->renderView(
          'emails/UserConfirmation.txt.twig',
          array('confCode' => $confCode)
          ),
          'text/plain'
          )
          */
          ;
          return $this->mailer->send($message);
          }
          }


          Third, to call it from the controller, make sure your controller is extending Controller and not the AbstractController! Crucial step!! Here is an example based on the parameters I require in my service:



          public function userConfirmation()
          {
          $emailService = $this->get('emailservice');
          $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
          return new Response('Success') //Or whatever you want to return
          }


          I hope this helps people. AbstractController does not give you the proper access to the service containers.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 '18 at 6:28









          Speedy059Speedy059

          1079




          1079

























              0














              Try :



              #config/services.yaml

              AppServiceEmailService
              arguments: ['@swiftmailer.mailer.default', '@twig']
              public: true


              And in your controller :



              public function userConfirmation(EmailService $emailService)
              {
              $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
              return new Response('Success') //Or whatever you want to return
              }


              You work with symfony 4.1 so you don't call service container in controller anymore ...
              https://symfony.com/doc/current/service_container/3.3-di-changes.html



              Also you can use FQCN "AppServiceMyService" to declare services in services.yaml and a proper legacy_aliases.yaml file to declare legacy aliases like "app.service.my.service" it helps keep your services.yaml clean in my opinion ...






              share|improve this answer


























                0














                Try :



                #config/services.yaml

                AppServiceEmailService
                arguments: ['@swiftmailer.mailer.default', '@twig']
                public: true


                And in your controller :



                public function userConfirmation(EmailService $emailService)
                {
                $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
                return new Response('Success') //Or whatever you want to return
                }


                You work with symfony 4.1 so you don't call service container in controller anymore ...
                https://symfony.com/doc/current/service_container/3.3-di-changes.html



                Also you can use FQCN "AppServiceMyService" to declare services in services.yaml and a proper legacy_aliases.yaml file to declare legacy aliases like "app.service.my.service" it helps keep your services.yaml clean in my opinion ...






                share|improve this answer
























                  0












                  0








                  0






                  Try :



                  #config/services.yaml

                  AppServiceEmailService
                  arguments: ['@swiftmailer.mailer.default', '@twig']
                  public: true


                  And in your controller :



                  public function userConfirmation(EmailService $emailService)
                  {
                  $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
                  return new Response('Success') //Or whatever you want to return
                  }


                  You work with symfony 4.1 so you don't call service container in controller anymore ...
                  https://symfony.com/doc/current/service_container/3.3-di-changes.html



                  Also you can use FQCN "AppServiceMyService" to declare services in services.yaml and a proper legacy_aliases.yaml file to declare legacy aliases like "app.service.my.service" it helps keep your services.yaml clean in my opinion ...






                  share|improve this answer












                  Try :



                  #config/services.yaml

                  AppServiceEmailService
                  arguments: ['@swiftmailer.mailer.default', '@twig']
                  public: true


                  And in your controller :



                  public function userConfirmation(EmailService $emailService)
                  {
                  $sent = $emailService->userConfirmation('some@emailaddress.com', '2ndParam');
                  return new Response('Success') //Or whatever you want to return
                  }


                  You work with symfony 4.1 so you don't call service container in controller anymore ...
                  https://symfony.com/doc/current/service_container/3.3-di-changes.html



                  Also you can use FQCN "AppServiceMyService" to declare services in services.yaml and a proper legacy_aliases.yaml file to declare legacy aliases like "app.service.my.service" it helps keep your services.yaml clean in my opinion ...







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 14 '18 at 11:08









                  Yoann MirYoann Mir

                  865




                  865






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53272302%2fsymfony-4-accessing-swift-mailer-in-service%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Post-Redirect-Get with Spring WebFlux and Thymeleaf

                      Xamarin.form Move up view when keyboard appear

                      JBPM : POST request for execute process go wrong