代码之家  ›  专栏  ›  技术社区  ›  Kareem Essawy

如何在symfony 4中正确调用带实例的函数

  •  -2
  • Kareem Essawy  · 技术社区  · 7 年前

    我正在尝试用smtp发送电子邮件 Symfony 4号 我有以下功能 docs 是的。

    public function send_smtp(\Swift_Mailer $mailer)
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('MyEmail@gmail.com')
            ->setBody('test email content');
        $mailer->send($message);
    }
    

    但是,我想从另一个函数调用这个函数,比如

    $this->send_smtp();
    

    但它抱怨“没有传递参数”

    $this->send_smtp(\Swift_Mailer);
    

    同时给出错误消息

    未定义常数'swift_mailer'

    问题是什么,怎么解决?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Frank B    7 年前

    有几种可能的解决办法。可以在操作中添加带有typehinting的参数,然后使用它调用函数:

    /**
     * @Route("/something")
     */
    public function something(\Swift_Mailer $mailer)
    {
        $this->send_smtp($mailer);
    }
    

    或者可以在send_smtp函数中从容器检索服务:

    public function send_smtp()
    {
        $mailer = $this->get('mailer');
    
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('MyEmail@gmail.com')
            ->setBody('test email content');
    
        $mailer->send($message);
    
    }
    
        2
  •  1
  •   Nikita Leshchev    7 年前

    创建服务,例如

    namespace App\Service\Mailer;
    
    class Mailer
    {
        private $mailer;
    
        public function __construct(\Swift_Mailer $mailer)
        {
            $this->mailer = $mailer;
        }
    
        public function send_smtp()
        {
            $message = (new \Swift_Message('Hello Email'))
                ->setFrom('send@example.com')
                ->setTo('MyEmail@gmail.com')
                ->setBody('test email content');
    
            $this->mailer->send($message);
        }
    }
    

    现在,您可以通过 __construct 以下内容:

    public function __construct(Mailer $mailer) 
    {
        $this->mailer = $mailer;
    }
    
    public function someAction()
    {
        $this->mailer->send_smtp()
    }
    

    也可以通过方法或属性注入。您可以在此处阅读有关注射的更多信息: https://symfony.com/doc/current/components/dependency_injection.html

    另外,我不建议你用容器法 get 因为这个方法只适用于公共服务,但是在symfony 4中,默认情况下服务是私有的。