【问题标题】:Laravel 5.1 access event object in listenerLaravel 5.1 在监听器中访问事件对象
【发布时间】:2015-07-22 17:12:33
【问题描述】:

我正在尝试 Laravel 5.1 的队列,在其侦听器中使用 $event 对象时遇到问题。

AuthController.php

public function postGenerateResetToken()
{
    try
    {
        $admin = Admin::where( 'email', '=', Input::get( 'email' ) )->firstOrFail();

        $token = Bus::dispatch( new GeneratePasswordResetToken( $admin ) );

        event( new PasswordResetTokenWasGenerated( $admin, $token ) );

        return success();
    }
    catch( ModelNotFoundException $exception )
    {
        return fail();
    }
}

PasswordResetTokenWasGenerated.php

class PasswordResetTokenWasGenerated extends Event
{

    use SerializesModels;

    public function __construct( $admin, $token )
    {
        $this->admin = $admin;
        $this->token = $token;
    }

    public function broadcastOn()
    {
        return [];
    }
}  

SendForgottenPasswordEmail.php

class SendForgottenPasswordEmail implements ShouldQueue
{

    public function __construct()
    {
        //
    }

    public function handle(PasswordResetTokenWasGenerated $event)
    {
        $data = [
            'admin' => $event->admin,
            'token' => $event->token
        ];

        Mail::send( 'emails.forgotten-password', $data, function( $message ) use ( $event )
        {
            $message->subject( 'Forgotten password' );

            $message->to( $event->admin->email );
        });
    }
}

在处理程序中使用$event->admin 会导致Undefined property: PasswordResetTokenWasGenerated::$admin

但是,这个错误只发生在我在监听器上实现ShouldQueue 接口时。没有界面也能正常工作。

队列驱动设置为sync

我知道这是因为队列,但它不应该按照我希望的方式工作吗?

【问题讨论】:

  • 能贴一下事件类的真实代码吗?您提供的是一些伪代码。

标签: laravel events queue listeners


【解决方案1】:

您应该在设置之前将您的管理员和令牌声明为公开:

class PasswordResetTokenWasGenerated 扩展事件 {

use SerializesModels;

public $admin;
public $token;

public function __construct( $admin, $token )
{
    $this->admin = $admin;
    $this->token = $token;
}

public function broadcastOn()
{
    return [];
}

}

之后,您应该能够在侦听器中访问这些属性。

【讨论】:

  • 太棒了!这实际上解决了这个问题。我不会发现这是因为“公共”是默认访问修饰符...但是,当然,反射将如何工作...谢谢!
猜你喜欢
  • 2020-11-29
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多