1

有没有办法在 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/databaseand illuminate/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); 
4

1 回答 1

2

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

$container = new Container();

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

$dispatcher = new Dispatcher($container);

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

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

于 2019-06-07T22:21:08.480 回答