使用ShouldQueue

时间:2015-10-30 08:01:04

标签: php laravel laravel-4 laravel-5

我的应用程序中有一个事件设置,用于在用户注册时发送激活电子邮件。它在没有ShouldQueue接口的情况下完美运行。但是,当我添加implements ShouldQueue时,我得到未定义的属性错误:

  

未定义的属性:App \ Events \ User \ UserCreated :: $ user

我使用的代码如下:

<?php

namespace App\Listeners\User;

use App\Events\User\UserCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\Email\EmailTemplateRepoInterface;
use App\Repos\User\UserRepoInterface;
use Request, Mail, DbView;

class UserCreatedEmail implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(EmailTemplateRepoInterface $template)
    {
        $this->template = $template;
    }

    /**
     * Handle the event.
     *
     * @param  UserCreated  $event
     * @return void
     */
    public function handle(UserCreated $event)
    {
        $user = $event->user;

        if($user)
        {
            if(!$user->status)
            {
                $user->activation_url = Request::root().'/activate/'.$user->activation_code;
                $template = $this->template->findTemplateByName('new_user_activation');
                $userArr = $user->toArray();
            }

            Mail::queue([], [], function ($message) use ($template, $userArr) 
            {
                $message->to($userArr['email'])
                    ->subject($template->subject)
                    ->setBody(DbView::make($template)->with($userArr)->render(), 'text/html');
            });
        }
    }
}

修改

以下是UserCreated课程:

<?php

namespace App\Events\User;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class UserCreated extends Event
{
    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($user, $row, $request)
    {
        $this->user = $user;
        $this->request = $request;
        $this->row = $row;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}

任何人都可以解释为什么当我尝试对电子邮件进行排队时会发生这种情况吗?

2 个答案:

答案 0 :(得分:8)

您需要将属性明确定义为public。即。

class UserCreated extends Event
{
    use SerializesModels;
    public $user;

...

答案 1 :(得分:0)

像rdiz一样,添加一个publicprotected属性。如果您仍然遇到问题,请注意Laravel Event具有一些保留的属性,例如sessionIdmessage。将参数名称更改为sessionId_可以为我解决。