有没有办法在 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/database
andilluminate/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);