【发布时间】:2015-01-29 16:15:12
【问题描述】:
我正在构建一个通过swiftmailer extension 发送电子邮件的 Yii2 应用程序。我将电子邮件设置(smtp、ssl、用户名等)存储在数据库表中,以便能够使用适当的视图对其进行编辑。 如何使用 db 表中的配置初始化 swiftmailer?
谢谢。
【问题讨论】:
标签: php initialization yii2 swiftmailer
我正在构建一个通过swiftmailer extension 发送电子邮件的 Yii2 应用程序。我将电子邮件设置(smtp、ssl、用户名等)存储在数据库表中,以便能够使用适当的视图对其进行编辑。 如何使用 db 表中的配置初始化 swiftmailer?
谢谢。
【问题讨论】:
标签: php initialization yii2 swiftmailer
您可以使用通过应用程序对象Yii::$app 提供的set() 方法初始化应用程序组件:
use Yii;
...
// Get config from db here
Yii::$app->set('mailer', [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
// Values from db
'host' => ...
'username' => ...
'password' => ...
'port' => ...
'encryption' => ...
],
]);
然后照常使用:
use Yii;
...
Yii::$app->mailer->...
如果您想为整个应用程序使用数据库中的相同配置,您可以在应用程序引导期间获取并应用此配置。
创建自定义类并将其放置在例如app/components;
namespace app\components;
use yii\base\BootstrapInterface;
class Bootstrap implements BootstrapInterface
{
public function bootstrap($app)
{
// Put the code above here but replace Yii::$app with $app
}
}
然后在配置中添加这个:
return [
[
'app\components\Bootstrap',
],
];
请注意:
如果已经存在具有相同 ID 的组件定义,它将是 覆盖。
官方文档:
【讨论】:
感谢@arogachev 的回答。这给了我一个想法,我解决了这个问题。我发布这个以帮助任何人
我解决了修改swiftmailer组件的问题,在Mailer.php中添加了这个:
use app\models\Administracion; //The model i needed for access bd
class Mailer extends BaseMailer
{
...
...
//this parameter is for the config (web.php)
public $CustomMailerConfig = false;
...
...
...
/**
* Creates Swift mailer instance.
* @return \Swift_Mailer mailer instance.
*/
protected function createSwiftMailer()
{
if ($this->CustomMailerConfig) {
$model = new Administracion();
$this->setTransport([
'class' => 'Swift_SmtpTransport',
'host' => $model->getSmtpHost(),
'username' => $model->getSmtpUser(),
'password' => $model->getSmtpPass(),
'port' => $model->getSmtpPort(),
'encryption' => $model->getSmtpEncryption(),
]);
}
return \Swift_Mailer::newInstance($this->getTransport());
}
并且在 Web.php 中添加了这个:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'enableSwiftMailerLogging' =>true,
'CustomMailerConfig' => true, //if its true use the bd config else set the transport here
'useFileTransport' => false,
],
【讨论】: