5

私はSymfony2とFOSUserBundleを使用しています

コントローラまたはそのアクションではないメーラークラスでSwiftMailerを使用して電子メールを送信する必要があります。コーディングしたものを表示しています

<?php

namespace Blogger\Util;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FlockMailer {


    public function SendEmail(){
        $message = \Swift_Message::newInstance()
        ->setSubject('Hello Email')
        ->setFrom('send@example.com')
        ->setTo('to@example.com')
        ->setBody('testing email');

        $this->get('mailer')->send($message);
    }
}

しかし、次のエラーが発生します

Fatal error: Call to undefined method Blogger\Util\FlockMailer::get() ....

どうすれば続行できますか?

4

2 に答える 2

8

編集:コードをテストしていないので、メーラーのインスタンスを取得するためにサービスコンテナーを使用しない場合は、トランスポート層も指定する必要があります。見てください:http://swiftmailer.org/docs/sending.html

あなたはそれを間違っています。基本的に、を拡張するクラスではなく、サービスControllerが必要です。サービスコンテナが機能していないため、SendMail()機能していません。

電子メールを送信するには、サービスコンテナを独自のカスタムヘルパーに挿入する必要があります。いくつかの例:

namespace Blogger\Util;

class MailHelper
{
    protected $mailer;

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

    public function sendEmail($from, $to, $body, $subject = '')
    {
        $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom($from)
            ->setTo($to)
            ->setBody($body);

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

コントローラアクションで使用するには:

services:
    mail_helper:
        class:     namespace Blogger\Util\MailHelper
        arguments: ['@mailer']

public function sendAction(/* params here */)
{
    $this->get('mail_helper')->sendEmail($from, $to, $body);
}

または、サービスコンテナにアクセスせずに他の場所:

class WhateverClass
{

    public function whateverFunction()
    {
        $helper = new MailerHelper(new \Swift_Mailer);
        $helper->sendEmail($from, $to, $body);
    }

}

または、コンテナにアクセスするカスタムサービスの場合:

namespace Acme\HelloBundle\Service;

class MyService
{
    protected $container;

    public function setContainer($container) { $this->container = $container; }

    public function aFunction()
    {
        $helper = $this->container->get('mail_helper');
        // Send email
    }
}

services:
    my_service:
        class: namespace Acme\HelloBundle\Service\MyService
        calls:
            - [setContainer,   ['@service_container']]
于 2012-04-20T13:15:48.023 に答える
1

セッターとゲッターのことは忘れてください。

$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$helper = new MailHelper($mailer);
$helper->sendEmail($from, $to, $body,$subject);

これは、リスナーメソッドから呼び出されたMailHelperでうまくいきました。

于 2014-10-12T13:59:12.773 に答える