Symfony 3 和 Swift Mailer:如何配置服务

Symfony 3 and Swift Mailer: how to configure service

在我的 symfony 项目中,我尝试配置电子邮件控制器但没有成功。

services.yml

emailController:        
    class:     AppBundle\Controller\emailController
    public: true
    arguments:            
        $mailer: '@mailer'

emailController.php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\UserBundle\FOSUserEvents;
use Doctrine\ORM\EntityManagerInterface;

class emailController extends Controller
{
    protected $mailer;

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


public function sendMail($email){

    $message = (new \Swift_Message())       
    ->setSubject('send mail')  
    ->setFrom('xx@yy.com')      
    ->setTo($email)
    ->setBody('TEST')
    ->setContentType("text/html");

    $this->mailer->send($message);

    return 1;       
}    

}

Symfony return 此消息:

Catchable Fatal Error: Argument 1 passed to AppBundle\Controller\emailController::__construct() must be an instance of Swift_Mailer, none given,

我尝试了一些配置和选项但没有成功

我认为问题在于,您正在将控制器配置为服务,但您的路由器可能不引用已配置的服务,仅引用 class 名称。

您可以使用注释:

@Route(service="emailController")

或将您的控制器称为服务的典型 yaml 格式:

email:
path:     /email
defaults: { _controller: emailController:indexAction }

请注意,两者都指的是您在上面的定义中指定的服务 ID,而不是实际的 class 名称。您可以在文档中阅读有关控制器即服务概念的更多信息:https://symfony.com/doc/current/controller/service.html

编辑: 作为旁注,因为您似乎使用的是新的 Symfony 版本,您可能需要检查使用 resolve_controller_arguments 标签将服务直接注入到操作中:https://symfony.com/doc/current/controller.html#fetching-services-as-controller-arguments

您将控制器定义为服务,这不是它的预期方式,而是无论如何;控制器和服务都正常PHP 类.

无论如何,上述错误消息说明了一切,您的服务定义需要提供正确的参数(none 给定),例如像那样:

arguments: ['@mailer']

请试试这个。