Laravel观察者-有什么方法可以传递其他参数? [英] Laravel Observers - Any way to pass additional arguments?

查看:248
本文介绍了Laravel观察者-有什么方法可以传递其他参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我使用Laravel模型事件观察者来触发自定义事件逻辑,但它们仅接受模型作为单个参数.我想做的是调用一个自定义事件,我还可以将一些额外的参数传递给该事件,从而将其传递给Observer方法.像这样:

So I'm using the Laravel model event observerables to fire custom event logic, but they only accept the model as a single argument. What I'd like to do is call a custom event that I can also pass some extra arguments to that would in turn get passed to the Observer method. Something like this:

    $this->fireModelEvent('applied', $user, $type);

然后在观察器中

    /**
     * Listen to the applied event.
     *
     * @param  Item    $item
     * @param  User    $user
     * @param  string  $type
     * @return void
     */
    public function applied(Item $item, $user, string $type) {
       Event::fire(new Applied($video, $user, $type));
    }

如您所见,我对传递执行此操作的用户感兴趣,这并不是必须创建该项目的用户.我不认为临时模型属性是答案,因为我的其他事件逻辑随着作业而排队,以保持尽可能短的响应时间.任何人都对如何扩展Laravel让我做到这一点有任何想法?

As you can see i'm interested in passing a user that performed this action, which is not the one that necessarily created the item. I don't think temporary model attributes are the answer because my additional event logic gets queued off as jobs to keep response time as low as possible. Anyone have any ideas on how I could extend Laravel to let me do this?

我的理论是做一个自定义特征,该特征会覆盖处理该逻辑的基本laravel模型类中的一个或多个函数.以为我在研究的过程中会发现是否还有其他人需要这样做.

My theory would be to do a custom trait that overrides one or more functions in the base laravel model class that handles this logic. Thought I'd see if anyone else has needed to do this while I look into it.

这也是文档参考

推荐答案

我已经通过使用特征实现一些自定义模型功能来完成此任务.

I've accomplished this task by implementing some custom model functionality using a trait.

/**
 * Stores event key data
 *
 * @var array
 */
public $eventData = [];


/**
 * Fire the given event for the model.
 *
 * @param  string  $event
 * @param  bool    $halt
 * @param  array   $data
 * @return mixed
 */
protected function fireModelEvent($event, $halt = true, array $data = []) {
  $this->eventData[$event] = $data;
  return parent::fireModelEvent($event, $halt);
}


/**
 * Get the event data by event
 *
 * @param  string  $event
 * @return array|NULL
 */
public function getEventData(string $event) {
  if (array_key_exists($event, $this->eventData)) {
    return $this->eventData[$event];
  }

  return NULL;
}

这篇关于Laravel观察者-有什么方法可以传递其他参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆