2016-07-30 103 views
1

我一直在研究laravel io(https://github.com/laravelio/laravel.io/tree/master/app/Forum/Threads)在論壇中創建線程的源代碼。首先請求ForumThreadController。控制器調用ThreadCreator類負責創建一個線程。這個類首先檢查線程主題和主體是否爲垃圾郵件。如果是垃圾郵件,則返回錯誤,否則會創建線程。laravel io源代碼設計模式

interface ThreadCreatorListener 
{ 
     public function threadCreationError(); 
     public function threadCreated(); 
} 

class ForumThreadController implements ThreadCreatorListener 
{ 
     public function __construct(ThreadCreator $threadCreator) 
     { 
      $this->threadCreator = $threadCreator; 
     } 

     public function threadCreationError() 
     { 
      return $this->redirectBack(['errors' => $errors]); 
     } 

     public function threadCreated($thread) 
     { 
      return $this->redirectAction('Forum\[email protected]', [$thread->slug]); 
     } 

     public function postCreateThread() 
     { 
       $threadSubject = $request->get('subject'); 
       $threadBody = $request->get('body'); 

       return $this->threadCreator->create($this , $threadSubject); 
     } 
} 

class ThreadCreator 
{ 
     private $spamDetector; 

     public function __construct(SpamDetector spamDetector) 
     { 
       $this->spamDetector = spamDetector; 
     } 

     public functin create(ThreadCreatorListener $listener , $subject) 
     { 
       if($this->spamDetector->isSpam($subject)) 
       { 
         return $listener->threadCreationError("Subject is spam"); 
       } 

       return $listener->threadCreated(); 
     } 

} 

我的問題是,爲什麼我應該通過在ThreadCreatorThreadCreatorListene R'我能得到什麼好處?類可以很容易地返回一些錯誤代碼,如返回數組('success'=> true,'message'=>'檢測到垃圾郵件');這將解決這個問題。

另外,這是一種設計模式?我用偵聽器設計模式搜索了一下,發現了觀察者的設計模式。

問候, 坦維爾

+1

請我沒有得到這樣的:'ForumThreadController :: postCreateThread()'什麼'$這個 - > threadCreator'?! –

+0

嗨,Ismail,這是ThreadCreator類的一個實例。我更新了我的代碼。請立即檢查。 – Rumel

+0

檢查你的AppServiceProvider或任何其他提供者,你會發現'ThreadCreatorListener'的綁定爲'ForumThreadController'解析,我猜! –

回答

1
  1. ThreadCreator處理,需要一個跟進的活動。爲了確保行動能夠得到,它要求一個可以稱之爲後續行動的對象。

  2. 代碼重用。如果您在整個應用程序中使用了很多ThreadCreator,您會發現自己對每次使用的結果都有反應。

    # bad - Easy to have out of date copy-paste 
    if ($has_spam == (new ThreadCreator($subject))) { 
        // do something 
        // maybe call a function 
    } 
    
    # good - Always obeys ForumThreadController 
    $thread_creator = (new ThreadCreator()) 
        ->create(new ForumThreadController, $subject);