Rumel
Rumel

Reputation: 319

Design pattern in laravel io source code

I have been studying laravel io(https://github.com/laravelio/laravel.io/tree/master/app/Forum/Threads) source code for creating a thread in a forum. At first the request comes to the ForumThreadController. The controller calls ThreadCreator class which is responsible for creating a Thread. This class at first checks thread subject and body for spam. If it is spam error is returned otherwise thread is created.

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\ForumThreadsController@getShowThread', [$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();
       }

}

My question is why should I pass a ThreadCreatorListener in ThreadCreator class ? What benefit do I get with this ? The class could easily return some error code like return array ('success' => true, 'message' => 'Spam detected'); which would solve the purpost.

Also, Is this some kind of design pattern ? I have googled with listener desing pattern and found observer design pattern.

Regards, Tanvir

Upvotes: 1

Views: 93

Answers (1)

Qevo
Qevo

Reputation: 2371

  1. ThreadCreator handles an activity that requires a follow up action. To ensure that action is going to be available it asks for an object on which it can call the follow up action.

  2. Code re-use. If you used many ThreadCreator throughout your app you would find yourself reacting to the result of each use.

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

Upvotes: 1

Related Questions