symfony中的电子邮件 - 我应该把代码放在哪里?!

时间:2011-07-28 22:00:00

标签: php email templates symfony1 symfony-1.4

我问了一个关于action.class.php变得非常庞大的问题。有很多有用的答案。你可以在这里阅读:Multiple action.class.php

由于action.class.php越来越大,可能存在一个问题,即它有很多东西。好的,我得到了模型,所以例如我可以将查询放入lib / model / doctrine / ...并移动几个表单。

在symfony中移动有关电子邮件的操作的最佳方法是什么!我应该把代码放在哪里?有没有更好的方法在symfony中发送电子邮件?

谢谢!

Craphunter

我的例子:

if ($this->form->isValid()) {
            $formData = $this->form->getValues();
            $firstname = $this->userdata->getFirstname();
            $lastname = $this->userdate->getLastname();

            try {
                $message = Swift_Message::newInstance()
                        ->setFrom('man@example.com')
                        ->setTo($this->shopdata->getEmail())
                        ->addReplyTo($this->userdata->getEmail())
                        ->setSubject($formData['subject'])
                        ->setBody($this->getPartial('emailcontact', $arguments = array(
                                    'firstname' => $firstname,
                                    'lastname' => $lastname,
                                    'message' => $formData['message'],
                                )));
                $this->getMailer()->send($message);
                $this->getUser()->setFlash('shop_name', $formData['email']);
                $this->getUser()->setFlash('name', $formData['name']);

            } catch (Exception $e) {

                $this->getUser()->setFlash('mailError', 'Technical Problem');
            }
            $this->redirect('aboutus/sendfeedbackthankyou');

1 个答案:

答案 0 :(得分:2)

我发现将发送代码放在扩展sfActions的主类中是有用的。我经常扔在整个项目中常用的所有内容(帮助ajax使用的代码等)。

特别是对于电子邮件,我有一个静态方法

public static function mail($options, $mailer) {

    sfProjectConfiguration::getActive()->loadHelpers('Partial');

    $required = array('subject', 'parameters', 'to_email', 'to_name', 'html', 'text');
    foreach ($required as $option)
    {
      if (!isset($options[$option])) {
        throw new sfException("Required option $option not supplied to ef3Actions::mail");
      }
    }

    $address = array();
    if (isset($options['from_name']) && isset($options['from_email'])) {
      $address['fullname'] = $options['from_name'];
      $address['email'] = $options['from_email'];
    } else
      $address = self::getFromAddress();


    if(!isset($options['body_is_partial']) || $options['body_is_partial']==true ){

      $message = Swift_Message::newInstance()
          ->setFrom(array($address['email'] => $address['fullname']))
          ->setTo(array($options['to_email'] => $options['to_name']))
          ->setSubject($options['subject'])
          ->setBody(get_partial($options['html'], $options['parameters']), 'text/html')
          ->addPart(get_partial($options['text'], $options['parameters']), 'text/plain');

    } else {

      $message = Swift_Message::newInstance()
          ->setFrom(array($address['email'] => $address['fullname']))
          ->setTo(array($options['to_email'] => $options['to_name']))
          ->setSubject($options['subject'])
          ->setBody($options['html'], 'text/html')
          ->addPart($options['text'], 'text/plain');

    }

    if (isset($options['cc']) && !is_null($options['cc'])) {
      if (is_array($options['cc'])) {
        foreach ($options['cc'] as $key => $value) {
          if (!is_number($key))
            $message->addCc($key, $value);
          else
            $message->addCc($value);
        }
      } elseif (is_string($options['cc'])) {
        $message->addCc($options['cc']);
      }
    }

    if (isset($options['bcc']) && !is_null($options['bcc'])) {
      if (is_array($options['bcc'])) {
        foreach ($options['bcc'] as $key => $value) {
          if (!is_number($key))
            $message->addBcc($key, $value);
          else
            $message->addBcc($value);
        }
      } elseif (is_string($options['bcc'])) {
        $message->addBcc($options['bcc']);
      }
    }

    if (isset($options['attachments'])) {
      $atts = $options['attachments'];
      if (is_array($atts)) {
        foreach ($atts as $att) {
          $message->attach(Swift_Attachment::fromPath($att));
        }
      } elseif (is_string($atts)) {
        $message->attach(Swift_Attachment::fromPath($atts));
      }
    }

    try
    {
      return $mailer->send($message);
    } catch (Exception $e)
    {
      throw new Exception("Erro ao tentar enviar um email: " . $e->getMessage());
    }

  }

为什么方法是静态的?好吧,我也一直在从事件监听器等其他环境中使用这种方法。发送电子邮件的典型呼叫类似于

  // SEND EMAIL FROM ACTION
$opts = array();
$opts['from_name'] = 'Webmaster';
$opts['from_email'] = 'from@email.com';

$variables = array();
// variables passed to the partial template
$variables['%client_firstname%'] = $firstName;
$variables['%client_lastname%'] = $lastName;
$variables['%client_email%'] = $client_email;
// preenche opcoes de envio
$opts['parameters'] = array();
$opts['body_is_partial'] = false;
$opts['to_name'] = $variables['%client_firstname%'] . " " . $variables['%client_lastname%'];
$opts['to_email'] = $variables['%client_email%'];
$opts['subject'] = __($subject, $variables);
$opts['html'] = __($message_html, $variables);
$opts['text'] = __($message_text, $variables);
if (isset($cc)) $opts['cc'] = $cc;
$bcc = sfDoctrineKeyValueProjectStore::get("{$contexto}_message_bcc");
if (isset($bcc)) $opts['bcc'] = $bcc;

return dcActions::mail($opts, sfContext::getInstance()->getMailer());

它还强制使用发送两个版本的电子邮件(html和文本)。使用这样的代码,您还可以使用partials来传递电子邮件。我发现它非常有用。