Laravel / Lumen |Не отправка события - PullRequest
0 голосов
/ 20 мая 2018

Я впервые использую события в Laravel / Lumen.

Я на самом деле использую Lumen и пытаюсь отправить экземпляр Mailable, когда новый пользователь регистрируется, чтобы отправить электронное письмо вbackground.

Я полагаю, что настроил все правильно, но я получаю эту ошибку ...

Ошибка типа: аргумент 1 передан в Illuminate \ Mail \ Mailable :: queue() должен реализовывать интерфейс Illuminate \ Contracts \ Queue \ Factory, экземпляр Illuminate \ Queue \ DatabaseQueue, заданный

В самом сообщении об ошибке я не могу видеть, откуда возникла проблема, например, существуетбез номеров строк.

Однако это мой код ...

AuthenticationContoller.php

$this->dispatch(new NewUser($user));

NewUser.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!');
      }
}

1 Ответ

0 голосов
/ 23 мая 2018

Я столкнулся с той же проблемой.Похоже, что 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);

...