Laravel 5.1在侦听器中访问事件对象

时间:2015-07-22 17:12:34

标签: laravel events queue listeners

我正在尝试使用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

但是,只有在Listener上实现ShouldQueue接口时才会出现此错误。没有界面就可以正常工作。

队列驱动程序设置为sync

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

1 个答案:

答案 0 :(得分:2)

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

class PasswordResetTokenWasGenerated扩展了Event {

use SerializesModels;

public $admin;
public $token;

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

public function broadcastOn()
{
    return [];
}

}

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