Laravel 5.1事件火灾

时间:2015-10-19 22:54:35

标签: php laravel laravel-5.1

我正在触发事件并使用这样的数组传递对象:

$event = new App\Events\SendMessage;
$event->msg = [ 'sender_id'=>'191', 
                'recepient_id'=>'190',
                'text'=>'some text',
              ];
Event::fire($event);

是否可以将此调用缩短一点并在一行中触发事件?

Event::fire(new App\Events\SendMessage([
                        'sender_id'=>'191', 
                        'recepient_id'=>'190',
                        'text'=>'some text',
                    ]));

4 个答案:

答案 0 :(得分:2)

您只需确保设置事件构造函数以填充该字段。

请参阅:http://laravel.com/docs/5.1/events#defining-events

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;

class SendMessage extends Event
{
    use SerializesModels;

    public $msg;
    public function __construct($msg)
    {
        $this->msg = $msg;
    }
}

答案 1 :(得分:1)

是的。只需传递__construct()

中的数据即可
class SendMessage extends Event
{
    protected $data;
    public function __construct(array $data)
    {
        $this->data = $data;
    }
}

答案 2 :(得分:1)

App\Events\SendMessage中,您需要定义构造函数方法,例如:

namespace App\Events;

class SendMessage {

    protected $data = null;

    public function __construct(Array $data)
    {
        $this->data = $data;
    }
}

答案 3 :(得分:0)

您可以在laravel中触发此类事件

只需将代码放入控制器

event(new App\Events\EventClassName());

如果您的事件具有参数,则

event(new App\Events\EventClassName(['first' => 'value','second' => 'value']));