2015-09-25 46 views
0

首先我想道歉,如果它是一個重複或重複的問題。Laravel依賴注入,使用設置功能

我是依賴注入的「新」。 我明白我是如何在__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); 
      } 
     } 
    }); 

我發現使用質量分配可以能幫助我:)

+1

我不確定在這裏看到依賴注入。 _may_限定的唯一的東西是PostWasCommented的論點,但我不認爲這就是你要求的。 –

回答

1

你這樣做是錯的。顧名思義,注入只有在之外注入依賴項纔有意義。

相反,你有什麼是setter注入方法setNotification()你從調用同一個類內的new Notification()對象作爲參數。

沒有進行注射。您的班級仍與Notification緊密配合,而setNotification()方法沒有任何用處。

+0

我該怎麼做?假設我想在每次foreach循環運行時注入新的Notification ... –

+0

如果您的對象需要消耗一堆'Notification'對象,那麼正確的方法是創建一個通知工廠對象並注入。 – lafor

+0

我想我理解你的意思,我很想得到更詳細的答案。我發現並將使用的解決方案更多地構建在框架Laravel - Mass Assignment中。 –

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

一定不要忘了加$可填寫的數組中的模型。

protected $fillable = ['from_id', 'from_id', 'to_id', 'type', 'source_id', 'parent_id', 'blog_name', 'my_post'];