有没有办法将参数发送给观察者?

Is there a way to send params to an observer?

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

基于 laravel 的文档:

User::observe(UserObserver::class);

observe 方法接收一个 class,不是一个对象的实例。所以我不能做类似的事情:

$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);
    }
}

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

Im not using laravel directly, but i'm using eloquent (illuminate/database and illuminate/events)

Im not trying to send additional parameters to an explicit event like in: , i'm trying to construct an observer with additional parameters.


完整解决方案:

感谢@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); 

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

$container = new Container();

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

$dispatcher = new Dispatcher($container);

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

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