2016-07-30 2 views
1

나는 포럼에서 스레드를 만들기위한 laravel io (https://github.com/laravelio/laravel.io/tree/master/app/Forum/Threads) 소스 코드를 연구 해왔다. 처음에 요청은 ForumThreadController에 있습니다. 컨트롤러는 스레드 생성을 담당하는 ThreadCreator 클래스를 호출합니다. 이 클래스는 우선 스레드 제목과 본문에서 스팸을 검사합니다. 스팸 일 경우 오류가 반환되고 그렇지 않으면 스레드가 만들어집니다. 내가 ThreadCreator 클래스의 ThreadCreatorListene R을 통과해야하는 이유디자인 패턴 in 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(); 
     } 

} 

내 질문은? 이걸로 내가 얻을 수있는 이점은 무엇입니까? 클래스는 반환 배열 ('success'=> true, 'message'=> 'Spam detected')과 같은 오류 코드를 쉽게 반환 할 수 있습니다. 그것은 전초 기지를 해결할 것입니다.

또한 디자인 패턴이 있습니까? 나는 경청자 desing 패턴으로 봤 거든 관찰자 디자인 패턴을 발견.

감사합니다, Tanvir

+1

내가 이것을하지 마십시오 :'ForumThreadController :: postCreateThread()에서''무엇을 $ this-> threadCreator'?! –

+0

안녕하세요, Ismail, 이것은 ThreadCreator 클래스의 인스턴스입니다. 내 코드를 업데이트했습니다. 지금 확인하십시오. – Rumel

+0

AppServiceProvider 나 다른 프로 바이더를 확인해 보면'ForumThreadController'를 해결하는'ThreadCreatorListener'에 대한 바인딩을 찾을 것입니다! –

답변

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