Which programming design pattern would suit this project?

Hello I’m looking for some guidance in choosing a programming design pattern to fit my current project.

I’m been trying for months to find a nice project to start using patterns properly and a little project I’ve just started seems to provide the perfect platform to learn from.

Basically I’m creating a Telegram Bot that will respond to users commands. That’s not the part I’m having problems with, it’s how best to structure my code so that adding new commands is clean and well structured.

I don’t need anyone to write any code for me, but is there a design pattern I could implement that would suit?

Here’s what I’m currently doing in puesudo code:

//Inbound Class

   public function inboundCommand($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;

    }

   } 


//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

   }

This works fine, but I feel that

  • I’m repeating a lot of code (bad)
  • Adding new commands means editing the “inbound class” file continuously. I think this breaks the open closed principle in SOLID.
  • The switch statement has a “code smell” to me.

I get very confused by all the names of the different type of patterns. Would someone advise me, which one would suit this scenario? I’m very happy to go and research about it and how it’s implemented, but I don’t want to go off on a goose chase and pick an unsuitable one because I don’t know any better!

Thank you.


Source: oop

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.