【问题标题】:Is there a way to send params to an observer?有没有办法将参数发送给观察者?
【发布时间】:2019-06-07 20:37:11
【问题描述】:

有没有办法在 Eloquent ORM 中向观察者发送参数?

基于 laravel 的文档:

User::observe(UserObserver::class);

observe 方法接收一个类,而不是一个对象的实例。所以我不能这样做:

$observer = new MyComplexUserObserver($serviceA, $serviceB)
User::observe($observer);

因此,在我的代码中,我可以执行以下操作:

class MyComplexUserObserver
{
    private $serviceA;
    private $serviceB;

    public function __constructor($serviceA, $serviceB){
        $this->serviceA = $serviceA;
        $this->serviceB = $serviceB;
    }

    public function created(User $user)
    {
        //Use parameters and services here, for example:
        $this->serviceA->sendEmail($user);
    }
}

有没有办法将参数或服务传递给模型观察者?

我没有直接使用laravel,但我使用的是eloquent(illuminate/databaseilluminate/events

我没有尝试向显式事件发送附加参数,例如:Laravel Observers - Any way to pass additional arguments?,我正在尝试使用附加参数构造一个观察者。


完整解决方案:

感谢@martin-henriksen。

use Illuminate\Container\Container as IlluminateContainer;

$illuminateContainer = new IlluminateContainer();
$illuminateContainer->bind(UserObserver::class, function () use ($container) {
    //$container is my project container
    return new UserObserver($container->serviceA, $container->serviceB);
});
$dispatcher = new Dispatcher($illuminateContainer);

Model::setEventDispatcher($dispatcher); //Set eventDispatcher for all models (All models extends this base model)
User::observe(UserObserver::class); 

【问题讨论】:

  • 我不明白解决方案。我把那个代码放在哪里?在模型中,在事件文件中还是在 AppServiceProvider 中?我尝试将其添加到 AppServiceProvider 并收到错误“无法实例化接口 Illuminate\Contracts\Events\Dispatcher”
  • 我使用了use Illuminate\Events\Dispatcher。为我工作。

标签: laravel eloquent illuminate-container


【解决方案1】:

在 Illuminate 事件中有 line,这表明在事件订阅时它会使用容器。这意味着我们可以利用它来发挥我们的优势,我对非 Laravel 引导应用程序不是很熟悉。但是,无论您的应用在哪里定义,您都会将您的类绑定到您自己的类。

$container = new Container();

$container->bind(MyComplexUserObserver::class, function ($app) {
    return new MyComplexUserObserver($serviceA, $serviceB, $theAnswerToLife);
});

$dispatcher = new Dispatcher($container);

这将导致,下次您的应用程序解析您的类时,它将使用它的这个版本,因此您可以按照您的意愿设置您的类。

编辑:一个如何利用 Laravel 容器来利用绑定功能的示例。

【讨论】:

  • 看来bind 方法是illuminate/container 的一部分,在laravel 中使用但我没有使用它......还有其他可能的解决方案吗?
  • 这是一个在 laravel 之外使用该应用程序的示例,我认为您正在使用它,因为它需要它用于事件使用的容器。 github.com/mattstauffer/Torch/blob/…
  • 我更新了答案,我认为你可以解决它
  • 谢谢!它起作用了:)(我已经用完整的解决方案更新了我的问题)
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多