Symfony 4 命令和 Swift Mailer 问题



我正在尝试自动调用发送电子邮件的控制器。所以我希望能够从symfony命令调用这个控制器。当我从浏览器调用 url 时,控制器函数起作用。但是当我从我的命令调用函数时,我从 Swift Mailer 收到错误,它要求我提供一个参数以构造 swift mailer($mailer(。

我试图在我的行动调用中注入\Swift_Mailer,但它只是向我展示了Swift_Transport的另一个参数错误。

以下是我的命令文件的代码以及控制器操作的签名和开头:

//../src/Command/mailCommand.php
class mailCommand extends Command {
//...
public function execute (InputInterface $input, OutputInterface $output) {
        $controller = new MailController();
        //try 1
        $controller->warningMailAction();
        //try 2
        //$transport = (new Swift_SmtpTransport('smtp://smtp.myadress.fr', 25));
        // $controller->warningMailAction(new Swift_Mailer($transport));
        $output->writeln('coucou !');
    }
}
//---------------------------------------
//../src/Controller/MailController.php
public function warningMailAction(Swift_Mailer $mailer) {}

我在symfony 4.3.2上运行,我不知道如何解决这个问题,我尝试的一切都会导致我出现更多错误。感谢每一个帮助,告诉我您是否需要更多我的代码来理解问题

Controller是一个ServiceSubscriber。这意味着在实例化时,容器会向其注入一些基本服务。

通过调用 new,您可以直接实例化它,而无需使用容器,并且它使用的服务不存在。您可以通过 setContainer 方法传递Container,或者只是将控制器注入到您的命令中,其实例化将由容器处理。

您只需要将控制器依赖项传递给命令__construct

use AppController;
class mailCommand extends Command 
{
    private $controller;
    public function __construct(MailController $mailController)
    {
        $this->controller = $mailController;
    }
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->controller->mailWarning(...);
        // Other stuff
    }
}

但是,控制器是特殊的,因为它们可以接收注入到其方法中的其他服务,就像mailWarning一样。这发生在控制器解析阶段。由于这将通过命令调用,因此您还必须处理此依赖项。与其手动实例化它,您还可以从容器中获取它:

public function __construct(MailController $mailController, SwiftMailer $mailer)

可以在服务容器参考中了解有关所有这些工作原理的详细信息。

我认为它有效。感谢您@msg的宝贵帮助。我将在这里发布我的最终代码,以防它对遇到同样麻烦的人有用。

这是我的邮件命令.php

public function __construct(MailController $mailController, Swift_Mailer $mailer)
{
    $this->controller = $mailController;
    $this->mailer = $mailer;
    parent::__construct();
}
protected function configure () {
    static $defaultName = 'app:mailAuto';
    $this->setName($defaultName);
    $this->setDescription("Permet d'envoyer des mails automatiquement lorsque le parc n'est pas à jour");
    $this->setHelp("Je serai affiche si on lance la commande bin/console app:mailAuto -h");
}
public function execute (InputInterface $input, OutputInterface $output) {
    $this->controller->warningMailAction($this->mailer);
    $output->writeln('Hello there !');
}

在我的控制器内部,我没有改变任何东西。我正常使用$mailer。

感谢所有帮助过我的人。

最新更新