【问题标题】:Symfony 3 and Swift Mailer: how to configure serviceSymfony 3 和 Swift Mailer:如何配置服务
【发布时间】:2017-11-27 09:44:17
【问题描述】:

在我的 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 返回此消息:

可捕获的致命错误:参数 1 传递给 AppBundle\Controller\emailController::__construct() 必须是 Swift_Mailer 的实例,没有给出,

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

【问题讨论】:

    标签: php symfony swiftmailer


    【解决方案1】:

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

    你可以使用注解:

    @Route(service="emailController")
    

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

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

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

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

    【讨论】:

      【解决方案2】:

      您将控制器定义为服务,这不是它的预期方式,而是任何方式;控制器和服务都是普通的 PHP 类。

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

      arguments: ['@mailer']
      

      请试试这个。

      【讨论】:

        猜你喜欢
        • 2019-05-25
        • 2019-11-30
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 2021-01-29
        • 1970-01-01
        • 2016-03-14
        相关资源
        最近更新 更多