我一直在研究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();
}
}
我的問題是,爲什麼我應該通過在ThreadCreator類ThreadCreatorListene R'我能得到什麼好處?類可以很容易地返回一些錯誤代碼,如返回數組('success'=> true,'message'=>'檢測到垃圾郵件');這將解決這個問題。
另外,這是一種設計模式?我用偵聽器設計模式搜索了一下,發現了觀察者的設計模式。
問候, 坦維爾
請我沒有得到這樣的:'ForumThreadController :: postCreateThread()'什麼'$這個 - > threadCreator'?! –
嗨,Ismail,這是ThreadCreator類的一個實例。我更新了我的代碼。請立即檢查。 – Rumel
檢查你的AppServiceProvider或任何其他提供者,你會發現'ThreadCreatorListener'的綁定爲'ForumThreadController'解析,我猜! –