Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mhopkins321's avatar

How to avoid massive switch statement when choosing a Class::method() from a string

We currently use slack and hubot at my office. Since I am better at php than I am at js/coffee I have our hubot passing commands to a laravel app so that I can do the heavy lifting there.

To make things easy on the hubot, all messages from slack are passed to a url.com/catchall route and then Push Queued to Iron.io, which is then Marshalled

    <?php namespace Idop\Http\Controllers;

    use Idop\Http\Requests;
    use Input;
    use Response;
    use Queue;

    class CatchAllController extends Controller {
        public function sterling(){
            $data = Input::all();
            Queue::push('\Idop\Catchall\Catchall',$data);
            return Response::json(['message'=>'success']);
        }

        public function queue(){
            return Queue::marshal();
        }
    }

And then on the return side

    <?php namespace Idop\Catchall;

    use Idop\Models\Message;

    class Catchall
    {
        public function fire($job,$data)
        {
            Message::create(['user' => $data['user'], 'message' => $data['message'], 'room' => $data['room']]);
        }
    }

Currently all I have it doing is logging the message. However if the message sterling deploy project@branch is passed I'd like to execute some certain code, and some entirely different code if sterling drizly beer me is passed. What is the best way to handle this sort of situation? A switch statement was my first thought, but with the amount of commands I'm looking at, it was getting super unweildy

0 likes
2 replies
mhopkins321's avatar

@moon0326 to answer your question of "why not?", no reason. A conditional that checks if its sterling deploy * could call the Deploy class and pass the rest of the statement in. That would certainly be a solution to a massive switch for all commands. I'm curious if that is the most ideal way to handle it or not, I think it may be

kfirba's avatar

If you want to avoid a massive switch statement you can use an associative array that the key is your sterling deploy blah blah and the value will be the method name.

Maybe you can play with it a-bit and have only the command name as the key and the method name as a value. This way, you can simply look for a single word in a string and figure out what method to invoke, if that makes sense to you.

Please or to participate in this conversation.