【发布时间】:2015-07-19 21:18:25
【问题描述】:
您好,我正在寻找适合我当前项目的编程设计模式的指导。
几个月来,我一直在努力寻找一个不错的项目来开始正确使用模式,而我刚刚开始的一个小项目似乎提供了一个完美的学习平台。
基本上,我正在创建一个可以响应用户命令的 Telegram Bot。这不是我遇到问题的部分,而是如何最好地构建我的代码,以便添加新命令时干净且结构良好。
我不需要任何人为我编写任何代码,但是我可以实现适合的设计模式吗?
这是我目前在 puesudo 中所做的(顺便说一句,我正在使用 Laravel)代码:
//routes.php
Route::post('inbound', ['uses' => 'inboundController@marshall']);
//inboundController.php
public function marshall($inboundMessage){
//Extract the command from the inbound message eg "start"
$command = extractfromtext($text);
//Get the user id from the person who sent the message
$userID = extractIdfromtext($text);
//Compare the command in a switch statement
switch ($command){
case (start):
return $result = new commandStart($userID)->fire();
break;
case (demo):
return $result = new commandDemo($userID)->fire();
break;
case (another):
return $result = new commandAnother($userID)->fire();
break;
default:
break;
}
}
//Each command has it's own class:
//Class commandStart
public function __construct($userID){
$this->userID = $userID
}
publin fuction fire(){
//send a picture to the userID
}
//Class commandDemo
public function __construct($userID){
$this->userID = $userID
}
publin fuction fire(){
//send a message to the userID
}
//Class commandAnother
public function __construct($userID){
$this->userID = $userID
}
publin fuction fire(){
//send a video to the userID
}
这很好,但我觉得
- 我重复了很多代码(不好)
- 添加新命令意味着不断编辑“入站类”文件。我认为这打破了 SOLID 中的开放封闭原则。
- switch 语句对我来说有一种“代码味道”。
我对不同类型模式的所有名称感到非常困惑。有人会建议我,哪一个适合这种情况?我很高兴去研究它以及它是如何实现的,但我不想去追逐一个不合适的,因为我不知道更好!
谢谢。
编辑:似乎在我试图使问题泛化时,我把它变得太迟钝了。我已经在使用 MVC 和 Larvel。这不是问题我认为 - 我想知道哪种设计模式可以让我轻松干净地添加更多命令 - 希望不必使用 switch 语句。
在阅读了一些回复之后,我想我开始明白该怎么做了。出于兴趣 - 下面建议的结构是实际设计模式还是只是良好的结构化代码?
【问题讨论】:
-
你尝试过MVC(Model-View-Controller)模型吗?
-
利用 function_exists() 和 class_exists(),这样添加新命令只需要一个带有 fire 方法的新类。它们都可以扩展一个抽象类,该类可以定义您的通用构造函数并强制子级实现 fire 方法
-
对不起,我不能帮助你使用 laravel,我不熟悉它。它被称为Abstract Factory Design Pattern 的设计模式
标签: php oop laravel design-patterns