Laravel。将参数传递给事件订阅者

时间:2015-03-05 15:37:18

标签: php events laravel-4 event-handling

开发一个任务系统,我希望将用户标记为任务并在用户请求任务时执行其他操作

我写了一个这样的任务事件订阅者

<?php namespace Athena\Events;

class TaskEventSubscriber {


    public function onCreate($event)
    {
       // Here we can send a lot of emails
    }


    public function onUpdate($event)
    {
        \Log::info('This is some useful information.');
    }

    public function onShow($event)
    {
        \Log::info('The view event is now triggerd ');
    }


    public function subscribe($events)
    {
        $events->listen('user.create', 'Athena\Events\TaskEventSubscriber@onCreate');

        $events->listen('user.update', 'Athena\Events\TaskEventSubscriber@onUpdate');

        $events->listen('task.show', 'Athena\Events\TaskEventSubscriber@onShow');
    }
}

我的控制器我这样开火:

public function show($id)
{
    $canView = $this->canView($id);
    if($canView !== true)
    {
        return $canView;
    }

    $task = $this->task->byId($id);
    // We fire the showed event
    $this->events->fire('task.show', $this->task);
    return View::make('tasks.show')
        ->with('task', $task);
}

但我不知道我怎么能抓住在事件中使用的参数

顺便说一句,我的任务事件订阅者在此服务提供商处注册

class AthenaServiceProvider extends ServiceProvider {

    public function register()
    {
        // A lot of stuffs
    }

    public function boot()
    {
        \Event::subscribe('Athena\Events\UserEventSubscriber');
        \Event::subscribe('Athena\Events\TaskEventSubscriber');
    }

}

如果您需要更多信息,请提前通知我

2 个答案:

答案 0 :(得分:2)

您需要声明一个像这样的

事件对象
<?php namespace App\Events;

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

class TriggerShowTask extends Event {

    use SerializesModels;

    public $task;

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

使用

触发事件时
\Event::fire(TriggerShowTask, $this->task);

$task对象将传递给事件

然后,您可以使用

在订阅者中访问它
public function onShow($event)
{
    $event->task; // A Task object
    \Log::info('The view event is now triggerd ');
}

答案 1 :(得分:0)

我不知道怎么感觉...... 我传递的值是我需要的事件,每个函数的$ event变量

注意:如果你需要发送多个值,只需将它们放入一个数组并设置你的事件函数来捕获它们就像参数一样

相关问题