php - Laravel/流明 | 未能分发事件
问题描述
这是我第一次在 Laravel/Lumen 中使用事件。
我实际上正在使用 Lumen,并且我试图在新用户注册时发送一个 Mailable 实例,以便在后台发送电子邮件。
我相信我设置正确,但我不断收到此错误...
类型错误:传递给 Illuminate\Mail\Mailable::queue() 的参数 1 必须实现接口 Illuminate\Contracts\Queue\Factory,给出 Illuminate\Queue\DatabaseQueue 的实例
我实际上无法在错误消息本身中看到问题来自哪里,例如没有行号。
但是,这是我的代码...
AuthenticationContoller.php
$this->dispatch(new NewUser($user));
新用户.php
<?php
namespace App\Mail;
use App\Models\User;
use Illuminate\Mail\Mailable;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class NewUser extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('test')->to('test@test.com', 'Test')
->from('test@test.com', 'test')->replyTo('test@test.com', 'test')
->subject('Welcome to the blog!');
}
}
解决方案
我遇到了同样的问题。Lumen 和 Illuminate/Mailer 似乎不能很好地协同工作。
不过,我在Github 线程中发现了一个非常简单的修复方法。
基本上你只需要在你的 app/Providers 目录中创建一个新的服务提供者。
MailServiceprovider.php
<?php
namespace App\Providers;
use Illuminate\Mail\Mailer;
use Illuminate\Mail\MailServiceProvider as BaseProvider;
class MailServiceProvider extends BaseProvider
{
/**
* Register the Illuminate mailer instance.
*
* @return void
*/
protected function registerIlluminateMailer()
{
$this->app->singleton('mailer', function ($app) {
$config = $app->make('config')->get('mail');
// 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 Mailer(
$app['view'], $app['swift.mailer'], $app['events']
);
// The trick
$mailer->setQueue($app['queue']);
// Next we will set all of the global addresses on this mailer, which allows
// for easy unification of all "from" addresses as well as easy debugging
// of sent messages since they get be sent into a single email address.
foreach (['from', 'reply_to', 'to'] as $type) {
$this->setGlobalAddress($mailer, $config, $type);
}
return $mailer;
});
$this->app->configure('mail');
$this->app->alias('mailer', \Illuminate\Contracts\Mail\Mailer::class);
}
}
然后你只需要在你的bootstrap/app.php
而不是默认的服务提供者中注册这个服务提供者,添加以下行:
$app->register(\App\Providers\MailServiceProvider::class);
推荐阅读
- go - 如何将 javascript 热重载集成到带有 https 的 golang 路由中以进行开发?
- excel - 用一些vba代码写,死路一条!得到错误结束块结束如果没有结束如果
- android - 创建没有停止点的旋转动画
- sql-server - Python 3.X micro ORM 兼容 SQL Server
- java - Android - 根据方向设置属性
- python - 按钮功能
- git - 合并到开发分支会导致功能分支被删除
- ios - UITableViewCell 子视图显示在单元格之外
- kubernetes - 带有 Hashicorp Vault 的 GKE - 可以使用 Google Cloud Run 吗?
- python-3.x - Python 3 和 Selenium - 如何组合多个 For 循环 - 抓取 Web 表