问题
I'm building a Yii2 application that sends email through the swiftmailer extension. I store the email settings (smtp, ssl, username, etc..) in a database table, to be able to edit them with an apposite view. How can I init swiftmailer with config from the db table?
Thank you.
回答1:
You can initialize application components using set() method available through application object Yii::$app
:
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' => ...
],
]);
Then use it as usual:
use Yii;
...
Yii::$app->mailer->...
If you want to use the same configuration from database for the whole application, you can get and apply this config during application bootstrap.
Create custom class and place it for example in 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
}
}
Then add this in config:
return [
[
'app\components\Bootstrap',
],
];
Note that:
If a component definition with the same ID already exists, it will be overwritten.
Official documentation:
- BootstrapInterface
- Mailer
回答2:
thanks to and @arogachev for his answer.that gave me an idea and i solve the problem. i Post this for help anyone
i solve the problem modyfing swiftmailer component, in Mailer.php added this:
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());
}
And in Web.php added this:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'enableSwiftMailerLogging' =>true,
'CustomMailerConfig' => true, //if its true use the bd config else set the transport here
'useFileTransport' => false,
],
来源:https://stackoverflow.com/questions/28219440/init-application-component-with-config-from-database