【发布时间】: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/database和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);
【问题讨论】:
-
我不明白解决方案。我把那个代码放在哪里?在模型中,在事件文件中还是在 AppServiceProvider 中?我尝试将其添加到 AppServiceProvider 并收到错误“无法实例化接口 Illuminate\Contracts\Events\Dispatcher”
-
我使用了
use Illuminate\Events\Dispatcher。为我工作。
标签: laravel eloquent illuminate-container