覆盖sendSwiftMessage()Laravel Swiftmailer定制
我使用Laravel 4.2覆盖sendSwiftMessage()Laravel Swiftmailer定制
通过user3158900给出的答案是Laravel 5. * 任何一个可以帮助我的4.2版本?
我想用我自己的函数重写sendSwiftMessage()受保护的函数。
sendSwiftMessage()位于
“供应商/ laravel /框架/ SRC /照亮/邮件/ Mailer.php”
我创建了一个
Lib/Mailer/CustomMailer.php
并将文件夹Lib设置为在作曲家(PSR4)中自动加载。 我现在可以通过编写在我的控制器中调用/加载我的功能:
new Lib \ Mailer \ CustomMailer;
这是我的文件看起来像:
Mail::send(xxxx);
:
<?php namespace Lib\Mailer;
class CustomMailer extends \Illuminate\Mail\Mailer {
/**
* Send a Swift Message instance.
*
* @param \Swift_Message $message
* @return void
*/
protected function sendSwiftMessage($message)
{
if (strpos($message->toString(), '[email protected]') == true) {
Log::info('Not sending mail to [email protected]');
}
else
{
if ($this->events)
{
$this->events->fire('mailer.sending', array($message));
}
if (! $this->pretending)
{
$this->swift->send($message, $this->failedRecipients);
}
elseif (isset($this->logger))
{
$this->logMessage($message);
}
}
}
}
然而,当我与Swiftmailer在我的控制器做实例发送电子邮件没有使用该sendSwiftMessage()函数
我的问题:我如何使Swiftmailer/Laravel在发送消息时使用我自定义的sendSwiftMessage()函数,如果我不想修改当前所有的控制器使用Mail :: send()代码
想我得到了这个想法,但我得到一个错误,但我认为这是对你的,因为你的自定义类正在使用一个不存在的属性,所以这里的解决方案无论如何。
在boot()
方法AppServiceProvider.php
,我已经添加了以下内容:
$this->app->singleton('customMailer', function($app) {
return new CustomMailer(
$app['view'], $app['swift.mailer'], $app['events']
);
});
在app/Lib/Mailer
文件夹中,我添加了另一个类的门面。
namespace App\Lib\Mailer;
use Illuminate\Support\Facades\Facade;
class Mail extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'customMailer';
}
}
在config/app.php
,我已经取代了Mail
别名有以下...
'Mail' => App\Lib\Mailer\Mail::class,
这应该是所有你需要做的。
另外一件事,我只注意到你的名字空间中缺少App
,这就解释了为什么你必须将Lib
文件夹添加到自动加载器。如果通过将App\
添加到开头来正确命名它以保持与PSR-4内联,则无需向composer.json
文件添加任何内容即可获取其他类。
你能告诉我AppServiceProvider.php应该位于哪里和文件的开头,谢谢!我正在尝试它,但仍然卡在那里 – raphjutras
哦,你正在使用Laravel 4.对不起,这段代码可能无法正常工作。 – user3158900
的确,我无法使它工作:( – raphjutras
user3158900的答案是Laravel 5. * 任何人都可以帮助我使用4.2版本? – raphjutras