为了这个例子,创建一个名为 ExtendedMailer 的新类,并将文件保存在自动加载器能够找到的位置。根据您放置文件的位置,您可能需要在保存文件后运行composer dump-autoload。
<?php
use Illuminate\Mail\Mailer;
class ExtendedMailer extends Mailer
{
protected function logMessage($message)
{
parent::logMessage($message);
$emails = implode(', ', array_keys((array) $message->getCc()));
$this->logger->info("Pretending to mail message to: {$emails}");
}
}
在您的应用程序能够加载类的地方创建一个新的服务提供者。如上,你可能需要运行composer dump-autoload
下面的代码只是扩展了原来的 MailServiceProvider 但允许我们在 IoC 中绑定一个不同的类,你会注意到 new ExtendedMailer;我们之前创建的类。显然,如果您为类命名,请在此处反映该更改。
<?php
use Illuminate\Mail\MailServiceProvider;
class ExtendedMailServiceProvider extends MailServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$me = $this;
$this->app->bindShared('mailer', function($app) use ($me)
{
$me->registerSwiftMailer();
// Once we have create the mailer instance, we will set a container instance
// on the mailer. This allows us to resolve mailer classes via containers
// for maximum testability on said classes instead of passing Closures.
$mailer = new ExtendedMailer(
$app['view'], $app['swift.mailer'], $app['events']
);
$this->setMailerDependencies($mailer, $app);
// If a "from" address is set, we will set it on the mailer so that all mail
// messages sent by the applications will utilize the same "from" address
// on each one, which makes the developer's life a lot more convenient.
$from = $app['config']['mail.from'];
if (is_array($from) && isset($from['address']))
{
$mailer->alwaysFrom($from['address'], $from['name']);
}
// Here we will determine if the mailer should be in "pretend" mode for this
// environment, which will simply write out e-mail to the logs instead of
// sending it over the web, which is useful for local dev environments.
$pretend = $app['config']->get('mail.pretend', false);
$mailer->pretend($pretend);
return $mailer;
});
}
}
在你的 config/app.php 中,你会发现一行看起来像
'Illuminate\Mail\MailServiceProvider',
您需要将其注释掉并添加如下一行
'ExtendedMailServiceProvider',
这样做的目的是将 Laravel 知道的邮件程序替换为您刚刚创建的邮件程序。您刚刚创建的与默认的相同,因为它只是对其进行了扩展,并向 logMessage 函数添加了功能。