首先,如果这是一个重复或重复的问题,我想道歉。
我是依赖注入的“新手”。 我理解我是如何在__constructor函数中完成它但不确定setter函数。 我想正确使用DI,问题是:我是否在以下代码中以正确的方式使用它:
public function setNotification(Notification $notification)
{
$this->notification = $notification;
}
public function handle(PostWasCommented $event)
{
$post = $event->comment->post;
$post->load('blog');
$followers = $post->followers;
$online_ids = Redis::pipeline(function($pipe) use ($event, $followers, $post)
{
foreach($followers as $follower){
if(Auth::id() != $follower->user_id){
$this->setNotification(new Notification());
$this->notification->from_id = Auth::id();
$this->notification->to_id = $follower->user_id;
$this->notification->type = 'PostComment';
$this->notification->source_id = $event->comment->id;
$this->notification->parent_id = $event->comment->post_id;
$this->notification->blog_name = $post->blog->link_name;
if($post->user_id == $follower->user_id)
$this->notification->my_post = true;
else
$this->notification->my_post = false;
$this->notification->save();
$pipe->get('user'.$follower->user_id);
}
}
});
我发现使用质量分配可以帮助我:)
答案 0 :(得分:1)
你做错了。顾名思义,注入只有从外部注入依赖才有意义。
相反,你所拥有的是一个setter注入方法setNotification()
,你可以在同一个类中使用new Notification()
对象作为参数从调用。
没有注射。您的课程仍与Notification
紧密结合,而setNotification()
方法无意义。
答案 1 :(得分:0)
我找到了解决方案,非常感谢所有信息:)
public function __construct(Notification $notification)
{
$this->notification = $notification;
}
public function handle(PostWasCommented $event)
{
$post = $event->comment->post;
$post->load('blog');
$followers = $post->followers;
$online_ids = Redis::pipeline(function($pipe) use ($event, $followers, $post)
{
foreach($followers as $follower){
if(Auth::id() != $follower->user_id){
$my_post = false;
if($post->user_id == $follower->user_id)
$my_post = true;
$this->notification->create([
'from_id' => Auth::id(),
'to_id' => $follower->user_id,
'type' => 'PostComment',
'source_id' => $event->comment->id,
'parent_id' => $event->comment->post_id,
'blog_name' => $post->blog->link_name,
'my_post' => $my_post
]);
$this->notification->save();
$pipe->get('user'.$follower->user_id);
}
}
});
一定不要忘记在模型中添加$ fillable数组。
protected $fillable = ['from_id', 'from_id', 'to_id', 'type', 'source_id', 'parent_id', 'blog_name', 'my_post'];