douqun1977 2013-06-20 14:43
浏览 22
已采纳

PHP AJAX聊天 - 聊天命令逻辑?

I've been developing a PHP ajax chat. I now want to add commands like /ban and so on.

But I am not sure how would I do that.

In the first place, I want the commands to start with a '/' sign.

Do I have to first check if the sent message is starting with a '/' sign, correct? And then see if the command 'ban' exists, but how will it know, where in the sentence, the username will be displayed in?

I am really confused, as I have no idea where and how to start. Is there a open source of commands system similar to my needs?

  • 写回答

2条回答 默认 最新

  • doulutian4843 2013-06-20 14:48
    关注

    You need to define a syntax for your commands yourself. For example /ban <username> for a ban.

    1. First you check whether the message begins with a slash. If so it is a command.
    2. Now search for the first space, everything after the slash and in front of the space is the command name.
    3. Pass everything after the first space to the command. In this case the username. The command handles the parameters on it's own.

    It could look like this:

    $message = '/ban TimWolla';
    if (substr($message, 0, 1) === '/') {
        // $message is a command
        $firstSpace = strpos($message, ' ');
        $command = substr($message, 1, $firstSpace);
        $parameters = substr($message, $firstSpace + 1);
    
        if (!hasPermission($command)) error('Permission denied');
    
        switch ($command) {
            case 'ban':
                ban($parameters);
            break;
        }
    } 
    

    In case you want to use proper OOP make each command a class and use an interface for all commands to require the proper methods. e.g.:

    interface Command {
        public function setParameters($parameters);
        public function hasPermission();
        public function execute();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?